1# @ohos.security.cryptoFramework (Crypto Framework) 2 3The **cryptoFramework** module shields underlying hardware and algorithm libraries and provides unified APIs for cryptographic operations. 4 5> **NOTE** 6> 7> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. 8 9## Modules to Import 10 11```ts 12import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 13``` 14 15## Result 16 17 Enumerates the operation results. 18 19 **System capability**: SystemCapability.Security.CryptoFramework 20 21| Name | Value | Description | 22| ------------------------------------- | -------- | ---------------------------- | 23| INVALID_PARAMS | 401 | Invalid parameter.<br>**Atomic service API**: This API can be used in atomic services since API version 11. | 24| NOT_SUPPORT | 801 | Unsupported operation.<br>**Atomic service API**: This API can be used in atomic services since API version 12. | 25| ERR_OUT_OF_MEMORY | 17620001 | Memory error.<br>**Atomic service API**: This API can be used in atomic services since API version 11. | 26| ERR_RUNTIME_ERROR | 17620002 | Runtime error.<br>**Atomic service API**: This API can be used in atomic services since API version 12. | 27| ERR_CRYPTO_OPERATION | 17630001 | Cryptographic operation error.<br>**Atomic service API**: This API can be used in atomic services since API version 11. | 28 29## DataBlob 30 31Defines a buffer array of the Binary Large Object (BLOB) type. 32 33 **Atomic service API**: This API can be used in atomic services since API version 11. 34 35 **System capability**: SystemCapability.Security.CryptoFramework 36 37| Name| Type | Readable| Writable| Description | 38| ---- | ---------- | ---- | ---- | ------ | 39| data | Uint8Array | Yes | Yes | Binary data array.| 40 41> **NOTE** 42> 43> The Uint8Array typed array represents an array of 8-bit unsigned integers. 44 45## ParamsSpec 46 47Encapsulates the parameters used for encryption or decryption. You need to construct its child class object and pass it to [init()](#init-2) for symmetric encryption or decryption. 48 49It applies to the symmetric cipher modes that require parameters such as the initialization vector (IV). If the IV is not required (for example, the ECB mode), pass in **null** to [init()](#init-2). 50 51**Atomic service API**: This API can be used in atomic services since API version 12. 52 53**System capability**: SystemCapability.Security.CryptoFramework.Cipher 54 55The supported system capability is SystemCapability.Security.CryptoFramework in API versions 9 to 11 and SystemCapability.Security.CryptoFramework.Cipher since API version 12. 56 57| Name | Type | Readable| Writable| Description | 58| ------- | ------ | ---- | ---- | ------------------------------------------------------------ | 59| algName | string | Yes | Yes | Algorithm for symmetric encryption or decryption. <br/>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.| 60 61> **NOTE** 62> 63> The **params** parameter in [init()](#init-2) is of the **ParamsSpec** type (parent class). However, a child class object (such as **IvParamsSpec**) needs to be passed in. When constructing the child class object, you need to set **algName** for its parent class **ParamsSpec** to specify the child class object to be passed to **init()**. 64 65## IvParamsSpec 66 67Defines the child class of [ParamsSpec](#paramsspec). It is a parameter of [init()](#init-2) for symmetric encryption or decryption. 68 69**IvParamsSpec** applies to the cipher modes such as CBC, CTR, OFB, and CFB, which use only the IV. 70 71**Atomic service API**: This API can be used in atomic services since API version 12. 72 73**System capability**: SystemCapability.Security.CryptoFramework.Cipher 74 75The supported system capability is SystemCapability.Security.CryptoFramework in API versions 9 to 11 and SystemCapability.Security.CryptoFramework.Cipher since API version 12. 76 77| Name| Type | Readable| Writable| Description | 78| ---- | --------------------- | ---- | ---- | ------------------------------------------------------------ | 79| iv | [DataBlob](#datablob) | Yes | Yes | IV for encryption or decryption.<br/>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| 80 81> **NOTE** 82> 83> Before passing **IvParamsSpec** to [init()](#init-2), specify **algName** for its parent class [ParamsSpec](#paramsspec). 84 85## GcmParamsSpec 86 87Defines the child class of [ParamsSpec](#paramsspec). It is a parameter of [init()](#init-2) for symmetric encryption or decryption. 88 89**GcmParamsSpec** applies to the GCM mode. 90 91**Atomic service API**: This API can be used in atomic services since API version 12. 92 93**System capability**: SystemCapability.Security.CryptoFramework.Cipher 94 95The supported system capability is SystemCapability.Security.CryptoFramework in API versions 9 to 11 and SystemCapability.Security.CryptoFramework.Cipher since API version 12. 96 97| Name | Type | Readable| Writable| Description | 98| ------- | --------------------- | ---- | ---- | ------------------------------------------------------------ | 99| iv | [DataBlob](#datablob) | Yes | Yes | IV, which is of 1 to 16 bytes. A 12-byte IV is commonly used. | 100| aad | [DataBlob](#datablob) | Yes | Yes | Additional authentication data (AAD), which is of 0 to INT_MAX bytes. A 16-byte AAD is commonly used. | 101| authTag | [DataBlob](#datablob) | Yes | Yes | Authentication tag, which is of 16 bytes.<br>If the GCM mode is used for encryption, **authTag** in the parameter **GcmParamsSpec** of [init()](#init-2) or [initSync()](#initsync12) is the last 16 bytes of [DataBlob](#datablob) output by [doFinal()](#dofinal-2) or [doFinalSync()](#dofinalsync12).| 102 103> **NOTE** 104> 105> - Before passing **GcmParamsSpec** to [init()](#init-2), specify **algName** for its parent class [ParamsSpec](#paramsspec). 106> - The IV to use is not length bound. However, the operation result depends on whether the underlying OpenSSL supports the IV. 107> - If **aad** is not required or the length of **aad** is **0**, you can set **aad** to an empty Uint8Array, that is, **aad: { data: new Uint8Array() }**. 108 109## CcmParamsSpec 110 111Defines the child class of [ParamsSpec](#paramsspec). It is a parameter of [init()](#init-2) for symmetric encryption or decryption. 112 113**CcmParamsSpec** applies to the CCM mode. 114 115**Atomic service API**: This API can be used in atomic services since API version 12. 116 117**System capability**: SystemCapability.Security.CryptoFramework.Cipher 118 119The supported system capability is SystemCapability.Security.CryptoFramework in API versions 9 to 11 and SystemCapability.Security.CryptoFramework.Cipher since API version 12. 120 121| Name | Type | Readable| Writable| Description | 122| ------- | --------------------- | ---- | ---- | ------------------------------------------------------------ | 123| iv | [DataBlob](#datablob) | Yes | Yes | IV, which is of 7 bytes. | 124| aad | [DataBlob](#datablob) | Yes | Yes | AAD, which is of 8 bytes. | 125| authTag | [DataBlob](#datablob) | Yes | Yes | Authentication tag, which is of 12 bytes.<br>If the CCM mode is used for encryption, **authTag** in the parameter [CcmParamsSpec](#ccmparamsspec) of [init()](#init-2) or [initSync()](#initsync12) is the last 12 bytes of [DataBlob](#datablob) output by [doFinal()](#dofinal-2) or [doFinalSync()](#dofinalsync12).| 126 127> **NOTE** 128> 129> Before passing **CcmParamsSpec** to [init()](#init-2), specify **algName** for its parent class [ParamsSpec](#paramsspec). 130 131## CryptoMode 132 133Enumerates the cryptographic operations. 134 135**Atomic service API**: This API can be used in atomic services since API version 12. 136 137**System capability**: SystemCapability.Security.CryptoFramework.Cipher 138 139The supported system capability is SystemCapability.Security.CryptoFramework in API versions 9 to 11 and SystemCapability.Security.CryptoFramework.Cipher since API version 12. 140 141| Name | Value | Description | 142| ------------ | ---- | ------------------ | 143| ENCRYPT_MODE | 0 | Encryption.| 144| DECRYPT_MODE | 1 | Decryption.| 145 146## AsyKeySpecItem<sup>10+</sup> 147 148Enumerates the asymmetric key parameters. 149 150**Atomic service API**: This API can be used in atomic services since API version 12. 151 152**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 153 154The supported system capability is SystemCapability.Security.CryptoFramework in API versions 10 to 11 and SystemCapability.Security.CryptoFramework.Key.AsymKey since API version 12. 155 156| Name | Value | Description | 157| ------------ | ---- | ---------------- | 158| DSA_P_BN | 101 | Prime modulus **p** in the DSA algorithm.| 159| DSA_Q_BN | 102 | Parameter **q**, prime factor of (p – 1) in the DSA algorithm.| 160| DSA_G_BN | 103 | Parameter **g** in the DSA algorithm.| 161| DSA_SK_BN | 104 | Private key **sk** in the DSA algorithm.| 162| DSA_PK_BN | 105 | Public key **pk** in the DSA algorithm.| 163| ECC_FP_P_BN | 201 | Prime number **p** in the **Fp** field of the elliptic curve in the ECC algorithm.| 164| ECC_A_BN | 202 | First coefficient **a** of the elliptic curve in the ECC algorithm.| 165| ECC_B_BN | 203 | Second coefficient **b** of the elliptic curve in the ECC algorithm.| 166| ECC_G_X_BN | 204 | X coordinate of the base point **g** in the ECC algorithm.| 167| ECC_G_Y_BN | 205 | Y coordinate of the base point **g** in the ECC algorithm.| 168| ECC_N_BN | 206 | Order **n** of the base point **g** in the ECC algorithm.| 169| ECC_H_NUM | 207 | Cofactor **h** in the ECC algorithm.| 170| ECC_SK_BN | 208 | Private key **sk** in the ECC algorithm.| 171| ECC_PK_X_BN | 209 | X coordinate of the public key **pk** (a point on the elliptic curve) in the ECC algorithm.| 172| ECC_PK_Y_BN | 210 | Y coordinate of the public key **pk** (a point on the elliptic curve) in the ECC algorithm.| 173| ECC_FIELD_TYPE_STR | 211 | Elliptic curve field type in the ECC algorithm. Currently, only the **Fp** field is supported.| 174| ECC_FIELD_SIZE_NUM | 212 | Size of the field in the ECC algorithm, in bits.<br>**NOTE**: The size of the **Fp** field is the length of the prime **p**, in bits.| 175| ECC_CURVE_NAME_STR | 213 | Standards for Efficient Cryptography Group (SECG) curve name in the ECC algorithm.| 176| RSA_N_BN | 301 | Modulus **n** in the RSA algorithm.| 177| RSA_SK_BN | 302 | Private key **sk** (private key exponent **d**) in the RSA algorithm.| 178| RSA_PK_BN | 303 | Public key **pk** (public key exponent **e**) in the RSA algorithm.| 179| DH_P_BN<sup>11+</sup> | 401 | Prime **p** in the DH algorithm.| 180| DH_G_BN<sup>11+</sup> | 402 | Parameter **g** in the DH algorithm.| 181| DH_L_NUM<sup>11+</sup> | 403 | Length of the private key in the DH algorithm, in bits.| 182| DH_SK_BN<sup>11+</sup> | 404 | Private key **sk** in the DH algorithm.| 183| DH_PK_BN<sup>11+</sup> | 405 | Public key **pk** in the DH algorithm.| 184| ED25519_SK_BN<sup>11+</sup> | 501 | Private key **sk** in the Ed25519 algorithm.| 185| ED25519_PK_BN<sup>11+</sup> | 502 | Public key **pk** in the Ed25519 algorithm.| 186| X25519_SK_BN<sup>11+</sup> | 601 | Private key **sk** in the X25519 algorithm.| 187| X25519_PK_BN<sup>11+</sup> | 602 | Public key **pk** in the X25519 algorithm.| 188 189## AsyKeySpecType<sup>10+</sup> 190 191Enumerates the key parameter types. 192 193**Atomic service API**: This API can be used in atomic services since API version 12. 194 195**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 196 197The supported system capability is SystemCapability.Security.CryptoFramework in API versions 10 to 11 and SystemCapability.Security.CryptoFramework.Key.AsymKey since API version 12. 198 199| Name | Value | Description | 200| ------------ | ---- | ---------------- | 201| COMMON_PARAMS_SPEC | 0 | Common parameter of the public and private keys. You can use [generateKeyPair()](#generatekeypair-2) to randomly generate a key pair based on the parameters of this type.| 202| PRIVATE_KEY_SPEC | 1 | Parameter of the private key. You can use [generatePriKey()](#generateprikey) to generate a private key based on the parameters of this type.| 203| PUBLIC_KEY_SPEC | 2 | Parameter of the public key. You can use [generatePubKey()](#generatepubkey) to generate a public key based on the parameters of this type.| 204| KEY_PAIR_SPEC | 3 | Full parameters of the public and private keys. You can use [generateKeyPair](#generatekeypair-2) to generate a key pair based on the parameters of this type.| 205 206## CipherSpecItem<sup>10+</sup> 207 208Enumerates the cipher parameters. You can use [setCipherSpec](#setcipherspec10) to set cipher parameters, and use [getCipherSpec](#getcipherspec10) to obtain cipher parameters. 209 210Currently, only RSA and SM2 are supported. Since API version 11, the **SM2_MD_NAME_STR** parameter is supported. For details, see [Asymmetric Key Encryption and Decryption Algorithm Specifications](../../security/CryptoArchitectureKit/crypto-asym-encrypt-decrypt-spec.md). 211 212**Atomic service API**: This API can be used in atomic services since API version 12. 213 214**System capability**: SystemCapability.Security.CryptoFramework.Cipher 215 216The supported system capability is SystemCapability.Security.CryptoFramework in API versions 10 to 11 and SystemCapability.Security.CryptoFramework.Cipher since API version 12. 217 218| Name | Value | Description | 219| ------------ | ---- | ---------------- | 220| OAEP_MD_NAME_STR | 100 | Message digest (MD) algorithm used with the PKCS1_OAEP padding mode in RSA.| 221| OAEP_MGF_NAME_STR | 101 | Mask generation algorithm used with the PKCS1_OAEP padding mode in RSA. Currently, only MGF1 is supported.| 222| OAEP_MGF1_MD_STR | 102 | MD algorithm for the MGF1 mask generation used with the PKCS1_OAEP padding mode in RSA.| 223| OAEP_MGF1_PSRC_UINT8ARR | 103 | **pSource** byte stream used with the PKCS1_OAEP padding mode in RSA.| 224| SM2_MD_NAME_STR<sup>11+</sup> | 104 | MD algorithm used in SM2.| 225 226## SignSpecItem<sup>10+</sup> 227 228Enumerates 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. 229 230Currently, only RSA and SM2 are supported. Since API version 11, the **SM2_USER_ID_UINT8ARR** parameter is supported. For details, see [Signing and Signature Verification Overview and Algorithm Specifications](../../security/CryptoArchitectureKit/crypto-sign-sig-verify-overview.md). 231 232**Atomic service API**: This API can be used in atomic services since API version 12. 233 234**System capability**: SystemCapability.Security.CryptoFramework.Signature 235 236The supported system capability is SystemCapability.Security.CryptoFramework in API versions 10 to 11 and SystemCapability.Security.CryptoFramework.Signature since API version 12. 237 238| Name | Value | Description | 239| ------------ | ---- | ---------------- | 240| PSS_MD_NAME_STR | 100 | MD algorithm used with the PSS padding mode in RSA.| 241| PSS_MGF_NAME_STR | 101 | Mask generation algorithm used with the PSS padding mode in RSA. Currently, only MGF1 is supported.| 242| PSS_MGF1_MD_STR | 102 | MD parameters for the MGF1 mask generation used with the PSS padding mode in RSA.| 243| PSS_SALT_LEN_NUM | 103 | Length of the salt in bytes used with the PSS padding mode in RSA.| 244| PSS_TRAILER_FIELD_NUM | 104 | Trailer field used in the encoding operation when PSS padding mode is used in RSA.| 245| SM2_USER_ID_UINT8ARR<sup>11+</sup> | 105 | User ID field in SM2.| 246 247## AsyKeySpec<sup>10+</sup> 248 249Defines the asymmetric key parameters for creating a key generator. You need to construct a child class object and pass it to [createAsyKeyGeneratorBySpec()](#cryptoframeworkcreateasykeygeneratorbyspec10) to create a key generator. When constructing a child class object, use little-endian format for RSA keys and use big-endian format and positive numbers for other key parameters of the bigint type. 250 251**Atomic service API**: This API can be used in atomic services since API version 12. 252 253**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 254 255The supported system capability is SystemCapability.Security.CryptoFramework in API versions 10 to 11 and SystemCapability.Security.CryptoFramework.Key.AsymKey since API version 12. 256 257| Name | Type | Readable| Writable| Description | 258| ------- | ------ | ---- | ---- | ------------------------------------------------------------ | 259| algName | string | Yes | Yes | Asymmetric key algorithm, for example, **RSA**, **DSA**, **ECC**, **SM2**, **Ed25519**, **X25519**, or **DH**.| 260| specType | [AsyKeySpecType](#asykeyspectype10) | Yes | Yes| Key parameter type, which is used to distinguish public and private key parameters.| 261 262## DSACommonParamsSpec<sup>10+</sup> 263 264Defines a child class of [AsyKeySpec](#asykeyspec10) used to specify the common parameters of the public and private keys in the DSA algorithm. It can be used to randomly generate a public or private key. 265 266To generate a key based on key parameters, pass it to [createAsyKeyGeneratorBySpec()](#cryptoframeworkcreateasykeygeneratorbyspec10) to create a key generator. 267 268**Atomic service API**: This API can be used in atomic services since API version 12. 269 270**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 271 272The supported system capability is SystemCapability.Security.CryptoFramework in API versions 10 to 11 and SystemCapability.Security.CryptoFramework.Key.AsymKey since API version 12. 273 274| Name | Type | Readable| Writable| Description | 275| ------- | ------ | ---- | ---- | ------------------------------------------------------------ | 276| p | bigint | Yes | Yes | Prime modulus **p** in the DSA algorithm.| 277| q | bigint | Yes | Yes | Parameter **q**, prime factor of (**p** – 1) in the DSA algorithm.| 278| g | bigint | Yes | Yes | Parameter **g** in the DSA algorithm.| 279 280## DSAPubKeySpec<sup>10+</sup> 281 282Defines a child class of [AsyKeySpec](#asykeyspec10) used to specify the parameters of the public key in the DSA algorithm. 283 284To generate a key based on key parameters, pass it to [createAsyKeyGeneratorBySpec()](#cryptoframeworkcreateasykeygeneratorbyspec10) to create a key generator. 285 286**Atomic service API**: This API can be used in atomic services since API version 12. 287 288**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 289 290The supported system capability is SystemCapability.Security.CryptoFramework in API versions 10 to 11 and SystemCapability.Security.CryptoFramework.Key.AsymKey since API version 12. 291 292| Name | Type | Readable| Writable| Description | 293| ------- | ------ | ---- | ---- | ------------------------------------------------------------ | 294| params | [DSACommonParamsSpec](#dsacommonparamsspec10) | Yes | Yes | Common parameters of the public and private keys in the DSA algorithm.| 295| pk | bigint | Yes | Yes | Public key in the DSA algorithm.| 296 297## DSAKeyPairSpec<sup>10+</sup> 298 299Defines a child class of [AsyKeySpec](#asykeyspec10) used to specify full parameters of the public and private keys in the DSA algorithm. 300 301To generate a key based on key parameters, pass it to [createAsyKeyGeneratorBySpec()](#cryptoframeworkcreateasykeygeneratorbyspec10) to create a key generator. 302 303**Atomic service API**: This API can be used in atomic services since API version 12. 304 305**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 306 307The supported system capability is SystemCapability.Security.CryptoFramework in API versions 10 to 11 and SystemCapability.Security.CryptoFramework.Key.AsymKey since API version 12. 308 309| Name | Type | Readable| Writable| Description | 310| ------- | ------ | ---- | ---- | ------------------------------------------------------------ | 311| params | [DSACommonParamsSpec](#dsacommonparamsspec10) | Yes | Yes | Common parameters of the public and private keys in the DSA algorithm.| 312| sk | bigint | Yes | Yes | Private key **sk** in the DSA algorithm.| 313| pk | bigint | Yes | Yes | Public key **pk** in the DSA algorithm.| 314 315## ECField<sup>10+</sup> 316 317Defines an elliptic curve field. Currently, only the **Fp** field is supported. 318 319**Atomic service API**: This API can be used in atomic services since API version 12. 320 321**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 322 323The supported system capability is SystemCapability.Security.CryptoFramework in API versions 10 to 11 and SystemCapability.Security.CryptoFramework.Key.AsymKey since API version 12. 324 325| Name | Type | Readable| Writable| Description | 326| ------- | ------ | ---- | ---- | ------------------------------------------------------------ | 327| fieldType | string | Yes | Yes | Type of the elliptic curve field. Currently, only **Fp** is supported.| 328 329## ECFieldFp<sup>10+</sup> 330 331Defines the prime field of the elliptic curve. It is a child class of [ECField](#ecfield10). 332 333**Atomic service API**: This API can be used in atomic services since API version 12. 334 335**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 336 337The supported system capability is SystemCapability.Security.CryptoFramework in API versions 10 to 11 and SystemCapability.Security.CryptoFramework.Key.AsymKey since API version 12. 338 339| Name | Type | Readable| Writable| Description | 340| ------- | ------ | ---- | ---- | ------------------------------------------------------------ | 341| p | bigint | Yes | Yes | Prime **p**.| 342 343## Point<sup>10+</sup> 344 345Defines a point on the elliptic curve. 346 347**Atomic service API**: This API can be used in atomic services since API version 12. 348 349**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 350 351The supported system capability is SystemCapability.Security.CryptoFramework in API versions 10 to 11 and SystemCapability.Security.CryptoFramework.Key.AsymKey since API version 12. 352 353| Name | Type | Readable| Writable| Description | 354| ------- | ------ | ---- | ---- | ------------------------------------------------------------ | 355| x | bigint | Yes | Yes | X coordinate of the point on an elliptic curve.| 356| y | bigint | Yes | Yes | Y coordinate of the point on an elliptic curve.| 357 358## ECCCommonParamsSpec<sup>10+</sup> 359 360Defines a child class of [AsyKeySpec](#asykeyspec10) used to specify the common parameters of the public and private keys in the ECC algorithm. It can be used to randomly generate a public or private key. 361 362To generate a key based on key parameters, pass it to [createAsyKeyGeneratorBySpec()](#cryptoframeworkcreateasykeygeneratorbyspec10) to create a key generator. 363 364**Atomic service API**: This API can be used in atomic services since API version 12. 365 366**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 367 368The supported system capability is SystemCapability.Security.CryptoFramework in API versions 10 to 11 and SystemCapability.Security.CryptoFramework.Key.AsymKey since API version 12. 369 370| Name | Type | Readable| Writable| Description | 371| ------- | ------ | ---- | ---- | ------------------------------------------------------------ | 372| field | [ECField](#ecfield10) | Yes | Yes | Field of the elliptic curve. Currently, only **Fp** is supported.| 373| a | bigint | Yes | Yes | First coefficient **a** of the elliptic curve.| 374| b | bigint | Yes | Yes | Second coefficient **b** of the elliptic curve.| 375| g | [Point](#point10) | Yes | Yes | Base point g.| 376| n | bigint | Yes | Yes | Order **n** of the base point **g**.| 377| h | number | Yes | Yes | Cofactor **h**.| 378 379## ECCPriKeySpec<sup>10+</sup> 380 381Defines a child class of [AsyKeySpec](#asykeyspec10) used to specify the parameters of the private key in the ECC algorithm. 382 383To generate a key based on key parameters, pass it to [createAsyKeyGeneratorBySpec()](#cryptoframeworkcreateasykeygeneratorbyspec10) to create a key generator. 384 385**Atomic service API**: This API can be used in atomic services since API version 12. 386 387**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 388 389The supported system capability is SystemCapability.Security.CryptoFramework in API versions 10 to 11 and SystemCapability.Security.CryptoFramework.Key.AsymKey since API version 12. 390 391| Name | Type | Readable| Writable| Description | 392| ------- | ------ | ---- | ---- | ------------------------------------------------------------ | 393| params | [ECCCommonParamsSpec](#ecccommonparamsspec10) | Yes | Yes | Common parameters of the public and private keys in the ECC algorithm.| 394| sk | bigint | Yes | Yes | Private key **sk** in the ECC algorithm.| 395 396## ECCPubKeySpec<sup>10+</sup> 397 398Defines a child class of [AsyKeySpec](#asykeyspec10) used to specify the parameters of the public key in the ECC algorithm. 399 400To generate a key based on key parameters, pass it to [createAsyKeyGeneratorBySpec()](#cryptoframeworkcreateasykeygeneratorbyspec10) to create a key generator. 401 402**Atomic service API**: This API can be used in atomic services since API version 12. 403 404**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 405 406The supported system capability is SystemCapability.Security.CryptoFramework in API versions 10 to 11 and SystemCapability.Security.CryptoFramework.Key.AsymKey since API version 12. 407 408| Name | Type | Readable| Writable| Description | 409| ------- | ------ | ---- | ---- | ------------------------------------------------------------ | 410| params | [ECCCommonParamsSpec](#ecccommonparamsspec10) | Yes | Yes | Common parameters of the public and private keys in the ECC algorithm.| 411| pk | [Point](#point10) | Yes | Yes | Public key **pk** in the ECC algorithm.| 412 413## ECCKeyPairSpec<sup>10+</sup> 414 415Defines a child class of [AsyKeySpec](#asykeyspec10) used to specify full parameters of the public and private keys in the ECC algorithm. 416 417To generate a key based on key parameters, pass it to [createAsyKeyGeneratorBySpec()](#cryptoframeworkcreateasykeygeneratorbyspec10) to create a key generator. 418 419**Atomic service API**: This API can be used in atomic services since API version 12. 420 421**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 422 423The supported system capability is SystemCapability.Security.CryptoFramework in API versions 10 to 11 and SystemCapability.Security.CryptoFramework.Key.AsymKey since API version 12. 424 425| Name | Type | Readable| Writable| Description | 426| ------- | ------ | ---- | ---- | ------------------------------------------------------------ | 427| params | [ECCCommonParamsSpec](#ecccommonparamsspec10) | Yes | Yes | Common parameters of the public and private keys in the ECC algorithm.| 428| sk | bigint | Yes | Yes | Private key **sk** in the ECC algorithm.| 429| pk | [Point](#point10) | Yes | Yes | Public key **pk** in the ECC algorithm.| 430 431## RSACommonParamsSpec<sup>10+</sup> 432 433Defines a child class of [AsyKeySpec](#asykeyspec10) used to specify the common parameters of the public and private keys in the RSA algorithm. It can be used to randomly generate a public or private key. 434 435To generate a key based on key parameters, pass it to [createAsyKeyGeneratorBySpec()](#cryptoframeworkcreateasykeygeneratorbyspec10) to create a key generator. 436 437**Atomic service API**: This API can be used in atomic services since API version 12. 438 439**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 440 441The supported system capability is SystemCapability.Security.CryptoFramework in API versions 10 to 11 and SystemCapability.Security.CryptoFramework.Key.AsymKey since API version 12. 442 443| Name | Type | Readable| Writable| Description | 444| ------- | ------ | ---- | ---- | ------------------------------------------------------------ | 445| n | bigint | Yes | Yes | Modulus **n**.| 446 447## RSAPubKeySpec<sup>10+</sup> 448 449Defines a child class of [AsyKeySpec](#asykeyspec10) used to specify the parameters of the public key in the RSA algorithm. 450 451To generate a key based on key parameters, pass it to [createAsyKeyGeneratorBySpec()](#cryptoframeworkcreateasykeygeneratorbyspec10) to create a key generator. 452 453**Atomic service API**: This API can be used in atomic services since API version 12. 454 455**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 456 457The supported system capability is SystemCapability.Security.CryptoFramework in API versions 10 to 11 and SystemCapability.Security.CryptoFramework.Key.AsymKey since API version 12. 458 459| Name | Type | Readable| Writable| Description | 460| ------- | ------ | ---- | ---- | ------------------------------------------------------------ | 461| params | [RSACommonParamsSpec](#rsacommonparamsspec10) | Yes | Yes | Common parameters of the public and private keys in the RSA algorithm.| 462| pk | bigint | Yes | Yes | Public key **pk** in the RSA algorithm.| 463 464## RSAKeyPairSpec<sup>10+</sup> 465 466Defines a child class of [AsyKeySpec](#asykeyspec10) used to specify full parameters of the public and private keys in the RSA algorithm. 467 468To generate a key based on key parameters, pass it to [createAsyKeyGeneratorBySpec()](#cryptoframeworkcreateasykeygeneratorbyspec10) to create a key generator. 469 470**Atomic service API**: This API can be used in atomic services since API version 12. 471 472**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 473 474The supported system capability is SystemCapability.Security.CryptoFramework in API versions 10 to 11 and SystemCapability.Security.CryptoFramework.Key.AsymKey since API version 12. 475 476| Name | Type | Readable| Writable| Description | 477| ------- | ------ | ---- | ---- | ------------------------------------------------------------ | 478| params | [RSACommonParamsSpec](#rsacommonparamsspec10) | Yes | Yes | Common parameters of the public and private keys in the RSA algorithm.| 479| sk | bigint | Yes | Yes | Private key **sk** in the RSA algorithm.| 480| pk | bigint | Yes | Yes | Public key **pk** in the RSA algorithm.| 481 482## ED25519PriKeySpec<sup>11+</sup> 483 484Defines a child class of [AsyKeySpec](#asykeyspec10) used to specify the parameters of the private key in the Ed25519 algorithm. 485 486To generate a key based on key parameters, pass it to [createAsyKeyGeneratorBySpec()](#cryptoframeworkcreateasykeygeneratorbyspec10) to create a key generator. 487 488**Atomic service API**: This API can be used in atomic services since API version 12. 489 490**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 491 492The supported system capability is SystemCapability.Security.CryptoFramework in API version 11 and SystemCapability.Security.CryptoFramework.Key.AsymKey since API version 12. 493 494| Name| Type | Readable| Writable| Description | 495| ---- | ------ | ---- | ---- | ------------------------- | 496| sk | bigint | Yes | Yes | Private key **sk** in the Ed25519 algorithm.| 497 498## ED25519PubKeySpec<sup>11+</sup> 499 500Defines a child class of [AsyKeySpec](#asykeyspec10) used to specify the parameters of the public key in the Ed25519 algorithm. 501 502To generate a key based on key parameters, pass it to [createAsyKeyGeneratorBySpec()](#cryptoframeworkcreateasykeygeneratorbyspec10) to create a key generator. 503 504**Atomic service API**: This API can be used in atomic services since API version 12. 505 506**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 507 508The supported system capability is SystemCapability.Security.CryptoFramework in API version 11 and SystemCapability.Security.CryptoFramework.Key.AsymKey since API version 12. 509 510| Name| Type | Readable| Writable| Description | 511| ---- | ------ | ---- | ---- | ------------------------- | 512| pk | bigint | Yes | Yes | Public key **pk** in the Ed25519 algorithm.| 513 514## ED25519KeyPairSpec<sup>11+</sup> 515 516Defines a child class of [AsyKeySpec](#asykeyspec10) used to specify full parameters of the public and private keys in the Ed25519 algorithm. 517 518To generate a key based on key parameters, pass it to [createAsyKeyGeneratorBySpec()](#cryptoframeworkcreateasykeygeneratorbyspec10) to create a key generator. 519 520**Atomic service API**: This API can be used in atomic services since API version 12. 521 522**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 523 524The supported system capability is SystemCapability.Security.CryptoFramework in API version 11 and SystemCapability.Security.CryptoFramework.Key.AsymKey since API version 12. 525 526| Name| Type | Readable| Writable| Description | 527| ---- | ------ | ---- | ---- | ------------------------- | 528| sk | bigint | Yes | Yes | Private key **sk** in the Ed25519 algorithm.| 529| pk | bigint | Yes | Yes | Public key **pk** in the Ed25519 algorithm.| 530 531## X25519PriKeySpec<sup>11+</sup> 532 533Defines a child class of [AsyKeySpec](#asykeyspec10) used to specify the parameters of the private key in the X25519 algorithm. 534 535To generate a key based on key parameters, pass it to [createAsyKeyGeneratorBySpec()](#cryptoframeworkcreateasykeygeneratorbyspec10) to create a key generator. 536 537**Atomic service API**: This API can be used in atomic services since API version 12. 538 539**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 540 541The supported system capability is SystemCapability.Security.CryptoFramework in API version 11 and SystemCapability.Security.CryptoFramework.Key.AsymKey since API version 12. 542 543| Name| Type | Readable| Writable| Description | 544| ---- | ------ | ---- | ---- | ------------------------ | 545| sk | bigint | Yes | Yes | Private key **sk** in the X25519 algorithm.| 546 547## X25519PubKeySpec<sup>11+</sup> 548 549Defines a child class of [AsyKeySpec](#asykeyspec10) used to specify the parameters of the public key in the X25519 algorithm. 550 551To generate a key based on key parameters, pass it to [createAsyKeyGeneratorBySpec()](#cryptoframeworkcreateasykeygeneratorbyspec10) to create a key generator. 552 553**Atomic service API**: This API can be used in atomic services since API version 12. 554 555**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 556 557The supported system capability is SystemCapability.Security.CryptoFramework in API version 11 and SystemCapability.Security.CryptoFramework.Key.AsymKey since API version 12. 558 559| Name| Type | Readable| Writable| Description | 560| ---- | ------ | ---- | ---- | ------------------------ | 561| pk | bigint | Yes | Yes | Public key **pk** in the X25519 algorithm.| 562 563## X25519KeyPairSpec<sup>11+</sup> 564 565Defines a child class of [AsyKeySpec](#asykeyspec10) used to specify full parameters of the public and private keys in the X25519 algorithm. 566 567To generate a key based on key parameters, pass it to [createAsyKeyGeneratorBySpec()](#cryptoframeworkcreateasykeygeneratorbyspec10) to create a key generator. 568 569**Atomic service API**: This API can be used in atomic services since API version 12. 570 571**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 572 573The supported system capability is SystemCapability.Security.CryptoFramework in API version 11 and SystemCapability.Security.CryptoFramework.Key.AsymKey since API version 12. 574 575| Name| Type | Readable| Writable| Description | 576| ---- | ------ | ---- | ---- | ------------------------ | 577| sk | bigint | Yes | Yes | Private key **sk** in the X25519 algorithm.| 578| pk | bigint | Yes | Yes | Public key **pk** in the X25519 algorithm.| 579 580## DHCommonParamsSpec<sup>11+</sup> 581 582Defines a child class of [AsyKeySpec](#asykeyspec10) used to specify the parameters of the public and private keys in the DH algorithm. 583 584To generate a key based on key parameters, pass it to [createAsyKeyGeneratorBySpec()](#cryptoframeworkcreateasykeygeneratorbyspec10) to create a key generator. 585 586**Atomic service API**: This API can be used in atomic services since API version 12. 587 588**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 589 590The supported system capability is SystemCapability.Security.CryptoFramework in API version 11 and SystemCapability.Security.CryptoFramework.Key.AsymKey since API version 12. 591 592| Name| Type | Readable| Writable| Description | 593| ---- | ------ | ---- | ---- | ----------------------------------- | 594| p | bigint | Yes | Yes | Large prime **p** in the DH algorithm. | 595| g | bigint | Yes | Yes | Parameter **g** in the DH algorithm. | 596| l | number | Yes | Yes | Length of the private key in the DH algorithm, in bits.| 597 598## DHPriKeySpec<sup>11+</sup> 599 600Defines a child class of [AsyKeySpec](#asykeyspec10) used to specify the parameters of the private key in the DH algorithm. 601 602To generate a key based on key parameters, pass it to [createAsyKeyGeneratorBySpec()](#cryptoframeworkcreateasykeygeneratorbyspec10) to create a key generator. 603 604**Atomic service API**: This API can be used in atomic services since API version 12. 605 606**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 607 608The supported system capability is SystemCapability.Security.CryptoFramework in API version 11 and SystemCapability.Security.CryptoFramework.Key.AsymKey since API version 12. 609 610| Name | Type | Readable| Writable| Description | 611| ------ | ------------------ | ---- | ---- | ------------------------------------ | 612| params | [DHCommonParamsSpec](#dhcommonparamsspec11) | Yes | Yes | Common parameters of the public and private keys in the DH algorithm.| 613| sk | bigint | Yes | Yes | Private key **sk** in the DH algorithm. | 614 615## DHPubKeySpec<sup>11+</sup> 616 617Defines a child class of [AsyKeySpec](#asykeyspec10) used to specify the parameters of the public key in the DH algorithm. 618 619To generate a key based on key parameters, pass it to [createAsyKeyGeneratorBySpec()](#cryptoframeworkcreateasykeygeneratorbyspec10) to create a key generator. 620 621**Atomic service API**: This API can be used in atomic services since API version 12. 622 623**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 624 625The supported system capability is SystemCapability.Security.CryptoFramework in API version 11 and SystemCapability.Security.CryptoFramework.Key.AsymKey since API version 12. 626 627| Name | Type | Readable| Writable| Description | 628| ------ | ------------------ | ---- | ---- | ------------------------------------ | 629| params | [DHCommonParamsSpec](#dhcommonparamsspec11) | Yes | Yes | Common parameters of the public and private keys in the DH algorithm.| 630| pk | bigint | Yes | Yes | Public key **pk** in the DH algorithm. | 631 632## DHKeyPairSpec<sup>11+</sup> 633 634Defines a child class of [AsyKeySpec](#asykeyspec10) used to specify full parameters of the public and private keys in the DH algorithm. 635 636To generate a key based on key parameters, pass it to [createAsyKeyGeneratorBySpec()](#cryptoframeworkcreateasykeygeneratorbyspec10) to create a key generator. 637 638**Atomic service API**: This API can be used in atomic services since API version 12. 639 640**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 641 642The supported system capability is SystemCapability.Security.CryptoFramework in API version 11 and SystemCapability.Security.CryptoFramework.Key.AsymKey since API version 12. 643 644| Name | Type | Readable| Writable| Description | 645| ------ | ------------------ | ---- | ---- | ------------------------------------ | 646| params | [DHCommonParamsSpec](#dhcommonparamsspec11) | Yes | Yes | Common parameters of the public and private keys in the DH algorithm.| 647| sk | bigint | Yes | Yes | Private key **sk** in the DH algorithm. | 648| pk | bigint | Yes | Yes | Public key **pk** in the DH algorithm. | 649 650## KdfSpec<sup>11+</sup> 651 652Defines the parameters of the key derivation function. When the key derivation function is used to derive a key, you need to construct and pass in a child class object of **KdfSpec**. 653 654**Atomic service API**: This API can be used in atomic services since API version 12. 655 656**System capability**: SystemCapability.Security.CryptoFramework.Kdf 657 658The supported system capability is SystemCapability.Security.CryptoFramework in API version 11 and SystemCapability.Security.CryptoFramework.Kdf since API version 12. 659 660| Name | Type | Readable| Writable| Description | 661| ------- | ------ | ---- | ---- | ------------------------------------------------------------ | 662| algName | string | Yes | Yes | Algorithm of the key derivation function, for example, **PBKDF2**.| 663 664## PBKDF2Spec<sup>11+</sup> 665 666Defines the child class of [KdfSpec](#kdfspec11). It is used as a parameter for PBKDF2 key derivation. 667 668**Atomic service API**: This API can be used in atomic services since API version 12. 669 670**System capability**: SystemCapability.Security.CryptoFramework.Kdf 671 672The supported system capability is SystemCapability.Security.CryptoFramework in API version 11 and SystemCapability.Security.CryptoFramework.Kdf since API version 12. 673 674| Name | Type | Readable| Writable| Description | 675| ------- | ------ | ---- | ---- | ------------------------------------------------------------ | 676| password | string \| Uint8Array | Yes | Yes | Original password entered by the user.| 677| salt | Uint8Array | Yes | Yes | Salt value.| 678| iterations | number | Yes | Yes | Number of iterations. The value must be a positive integer.| 679| keySize | number | Yes | Yes | Length of the derived key, in bytes.| 680 681> **NOTE** 682> 683> **password** specifies the original password. If **password** is of the string type, pass in the data used for key derivation rather than a string of the HexString or Base64 type. In addition, the string must be in utf-8 format. Otherwise, the key derived may be different from the one expected. 684 685## HKDFSpec<sup>12+</sup> 686 687Defines the child class of [KdfSpec](#kdfspec11). It is a parameter for HKDF key derivation. 688 689**Atomic service API**: This API can be used in atomic services since API version 12. 690 691**System capability**: SystemCapability.Security.CryptoFramework.Kdf 692 693| Name | Type | Readable| Writable| Description | 694| ------- | ------ | ---- | ---- | ------------------------------------------------------------ | 695| key | string \| Uint8Array | Yes | Yes | Key material.| 696| salt | Uint8Array | Yes | Yes | Salt value.| 697| info | Uint8Array | Yes | Yes | Information used to expand the key.| 698| keySize | number | Yes | Yes | Length of the derived key, in bytes.| 699 700> **NOTE** 701> 702> **key** is the original key material entered by the user. **info** and **salt** are optional. An empty string can be passed in based on the mode. 703> 704> For example, if the mode is **EXTRACT_AND_EXPAND**, all parameter values must be passed in. If the mode is **EXTRACT_ONLY**, **info** can be empty. When **HKDFspec** is constructed, pass in **null** to **info**. 705> 706> The default mode is **EXTRACT_AND_EXPAND**. The value **HKDF|SHA256|EXTRACT_AND_EXPAND** is equivalent to **HKDF|SHA256**. 707 708## ScryptSpec<sup>18+</sup> 709 710Defines the child class of [KdfSpec](#kdfspec11). It is a parameter for scrypt key derivation function (KDF). 711 712**Atomic service API**: This API can be used in atomic services since API version 18. 713 714**System capability**: SystemCapability.Security.CryptoFramework.Kdf 715 716| Name | Type | Read-Only| Optional| Description | 717| ------- | ------ | ---- | ---- | ------------------------------------------------------------ | 718| passphrase | string \| Uint8Array | Yes | No | Original password entered by the user.| 719| salt | Uint8Array | Yes | No | Salt value.| 720| n | number | Yes | No | Number of iterations. The value must be a positive integer.| 721| p | number | Yes | No | Parallelization parameter. The value must be a positive integer.| 722| r | number | Yes | No | Block size. The value must be a positive integer.| 723| maxMemory | number | Yes | No | Maximum memory size. The value must be a positive integer.| 724| keySize | number | Yes | No | Length of the derived key, in bytes. The value must be a positive integer.| 725 726> **NOTE** 727> 728> **passphrase** specifies the original password. If **password** is of the string type, pass in the data used for key derivation rather than a string of the HexString or Base64 type. In addition, the string must be in utf-8 format. Otherwise, the key derived may be different from the one expected. 729 730## SM2CipherTextSpec<sup>12+</sup> 731 732Represents the SM2 ciphertext parameters. You can use this object to generate SM2 ciphertext in ASN.1 format or obtain SM2 parameters from the SM2 ciphertext in ASN.1 format. 733 734**Atomic service API**: This API can be used in atomic services since API version 12. 735 736**System capability**: SystemCapability.Security.CryptoFramework.Cipher 737 738| Name | Type | Readable| Writable| Description | 739| ------- | ------ | ---- | ---- | ------------------------------------------------------------ | 740| xCoordinate | bigint | Yes | Yes | Coordinate X.| 741| yCoordinate | bigint | Yes | Yes | Coordinate Y.| 742| cipherTextData | Uint8Array | Yes | Yes | Ciphertext.| 743| hashData | Uint8Array | Yes | Yes | Hash value.| 744 745> **NOTE** 746> 747> - **hashData** is a value obtained by applying the SM3 algorithm to the plaintext. It has a fixed length of 256 bits. 748> 749> - **cipherTextData** is the ciphertext with the same length as the plaintext. 750> 751> - During the generation of ciphertext in C1C3C2 format, if the length of x (**C1_X**) or y (**C1_Y**) is less than 32 bytes, zeros must be added to the high-order bits to extend them to 32 bytes. 752 753## KeyEncodingConfig<sup>18+</sup> 754Represents the RSA private key encoding parameters. You can use it to generate an encoded private key string with the specified algorithm and password. 755 756**Atomic service API**: This API can be used in atomic services since API version 18. 757 758**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 759 760| Name | Type | Read-Only| Optional| Description | 761| ------- | ------ | ---- | ---- | ------------------------------------------------------------ | 762| password | string | Yes | No | Password used for encoding the private key.| 763| cipherName | string | Yes | No | Algorithm to use.| 764 765> **NOTE** 766> 767> - **password** specifies the password used for encoding the private key. It is mandatory. 768> 769> - **cipherName** specifies the algorithm used for encoding. It is mandatory. Currently, only **AES-128-CBC**, **AES-192-CBC**, **AES-256-CBC**, and **DES-EDE3-CBC** are supported. 770 771## MacSpec<sup>18+</sup> 772Represents the message authentication code (MAC) parameters. You need to construct a child class object and use it as a parameter when generating a Hash-based Message Authentication Code (HMAC) or Cipher-based Message Authentication Code (CMAC). 773 774**Atomic service API**: This API can be used in atomic services since API version 18. 775 776**System capability**: SystemCapability.Security.CryptoFramework.Mac 777 778| Name | Type | Read-Only| Optional| Description | 779| ------- | ------ | ---- | ---- | ------------------------------------------------------------ | 780| algName | string | Yes | No | Algorithm to use.| 781 782> **NOTE** 783> 784> **algName** specifies the algorithm used for generating a MAC. It is mandatory. 785 786## HmacSpec<sup>18+</sup> 787Represents the child class of [MacSpec](#macspec18). It is used as an input parameter for HMAC generation. 788 789**Atomic service API**: This API can be used in atomic services since API version 18. 790 791**System capability**: SystemCapability.Security.CryptoFramework.Mac 792 793| Name | Type | Read-Only| Optional| Description | 794| ------- | ------ | ---- | ---- | ------------------------------------------------------------ | 795| mdName | string | Yes | No | MD algorithm to use.| 796 797> **NOTE** 798> 799> **mdName** specifies the MD algorithm used by the HMAC. It is mandatory. 800 801## CmacSpec<sup>18+</sup> 802Represents the child class of [MacSpec](#macspec18). It is used as an input parameter for CMAC generation. 803 804**Atomic service API**: This API can be used in atomic services since API version 18. 805 806**System capability**: SystemCapability.Security.CryptoFramework.Mac 807 808| Name | Type | Read-Only| Optional| Description | 809| ------- | ------ | ---- | ---- | ------------------------------------------------------------ | 810| cipherName | string | Yes | No | Symmetric encryption algorithm to use.| 811 812> **NOTE** 813> 814> **cipherName** specifies the symmetric encryption algorithm used by the CMAC. It is mandatory. 815 816## Key 817 818Provides 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. 819 820Keys can be generated by a key generator. 821 822### Attributes 823 824**Atomic service API**: This API can be used in atomic services since API version 12. 825 826**System capability**: SystemCapability.Security.CryptoFramework.Key 827 828The supported system capability is SystemCapability.Security.CryptoFramework in API versions 9 to 11 and SystemCapability.Security.CryptoFramework.Key since API version 12. 829 830| Name | Type | Readable| Writable| Description | 831| ------- | ------ | ---- | ---- | ---------------------------- | 832| format | string | Yes | No | Format of the key. | 833| algName | string | Yes | No | Algorithm to use. This parameter contains the key length if the key is a symmetric key.| 834 835### getEncoded 836 837getEncoded(): DataBlob 838 839Obtains the byte stream of the key data. This API returns the result synchronously. The key can be a symmetric key, public key, or private key. The public key must be in DER encoding format and comply with the ASN.1 syntax and X.509 specifications. The private key must be in DER encoding format and comply with the ASN.1 syntax and PKCS#8 specifications. 840 841> **NOTE** 842> 843> When a key parameter is used to generate an RSA private key, the private key object does not support **getEncoded()**. 844 845**Atomic service API**: This API can be used in atomic services since API version 12. 846 847**System capability**: SystemCapability.Security.CryptoFramework.Key 848 849The supported system capability is SystemCapability.Security.CryptoFramework in API versions 9 to 11 and SystemCapability.Security.CryptoFramework.Key since API version 12. 850 851**Return value** 852 853| Type | Description | 854| --------------------- | ------------------------ | 855| [DataBlob](#datablob) | Key obtained.| 856 857**Error codes** 858For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 859 860| ID| Error Message | 861| -------- | ---------------------- | 862| 801 | this operation is not supported. | 863| 17620001 | memory error. | 864| 17630001 | crypto operation error. | 865 866**Example** 867 868```ts 869import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 870 871async function testGenerateAesKey() { 872 let symKeyGenerator = cryptoFramework.createSymKeyGenerator('AES256'); 873 let symKey = await symKeyGenerator.generateSymKey(); 874 let encodedKey = symKey.getEncoded(); 875 console.info('key hex:' + encodedKey.data); 876} 877``` 878 879## SymKey 880 881Provides 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. 882 883Symmetric keys can be generated by a [SymKeyGenerator](#symkeygenerator). 884 885### clearMem 886 887clearMem(): void 888 889Clears 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. 890 891**Atomic service API**: This API can be used in atomic services since API version 12. 892 893**System capability**: SystemCapability.Security.CryptoFramework.Key.SymKey 894 895The supported system capability is SystemCapability.Security.CryptoFramework in API versions 9 to 11 and SystemCapability.Security.CryptoFramework.Key.SymKey since API version 12. 896 897**Example** 898 899<!--code_no_check--> 900```ts 901let key: cryptoFramework.SymKey; // The key is generated by a symKeyGenerator. The generation process is omitted here. 902let encodedKey = key.getEncoded(); 903console.info('key blob: '+ encodedKey.data); // Display key content. 904key.clearMem(); 905encodedKey = key.getEncoded(); 906console.info('key blob: ' + encodedKey.data); // Display all 0s. 907``` 908 909## PubKey 910 911Provides APIs for public key operations. **PubKey** is a child class of [Key](#key). It needs to be passed in during asymmetric encryption and decryption, signature verification, and key agreement. 912 913The public key can be generated by using the asymmetric key generator [AsyKeyGenerator](#asykeygenerator) or [AsyKeyGeneratorBySpec](#asykeygeneratorbyspec10). 914 915### getAsyKeySpec<sup>10+</sup> 916 917getAsyKeySpec(itemType: AsyKeySpecItem): bigint | string | number 918 919Obtains a key parameter. This API returns the result synchronously. 920 921**Atomic service API**: This API can be used in atomic services since API version 12. 922 923**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 924 925The supported system capability is SystemCapability.Security.CryptoFramework in API versions 10 to 11 and SystemCapability.Security.CryptoFramework.Key.AsymKey since API version 12. 926 927**Parameters** 928 929| Name| Type | Mandatory| Description | 930| ---- | --------------------- | ---- | -------------------- | 931| itemType | [AsyKeySpecItem](#asykeyspecitem10) | Yes | Key parameter to obtain.| 932 933**Return value** 934 935| Type | Description | 936| --------------------------- | --------------------------------- | 937| bigint \| string \| number | Content of the key parameter obtained.| 938 939**Error codes** 940For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 941 942| ID| Error Message | 943| -------- | ---------------------- | 944| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 945| 17620001 | memory error. | 946| 17630001 | crypto operation error. | 947 948**Example** 949 950<!--code_no_check--> 951```ts 952let key: cryptoFramework.PubKey; // key is a public key object. The generation process is omitted here. 953let p = key.getAsyKeySpec(cryptoFramework.AsyKeySpecItem.ECC_FP_P_BN); 954console.info('ecc item --- p: ' + p.toString(16)); 955``` 956 957### getEncodedDer<sup>12+</sup> 958 959getEncodedDer(format: string): DataBlob 960 961Obtains the public key data that complies with the ASN.1 syntax and DER encoding based on the specified format (such as the specification to use and whether to compress the key). Currently, only compressed and uncompressed ECC public key data can be obtained. 962 963> **NOTE** 964> 965> The difference between [Key.getEncoded()](#getencoded) and this API is as follows:<br> 966> - You can specify the format of the data to obtain in this API. 967> - The format of the key to obtain cannot be specified in [Key.getEncoded()](#getencoded). That is, the format of the data obtained must be the same as that of the original data. The original data format is the format of the key object generated by [convertKey](#convertkey-3). 968 969**Atomic service API**: This API can be used in atomic services since API version 12. 970 971**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 972 973**Parameters** 974 975| Name| Type | Mandatory| Description | 976| ---- | --------------------- | ---- | -------------------- | 977| format | string | Yes | Format of the key. The value can be **X509\|COMPRESSED** or **X509\|UNCOMPRESSED** only.| 978 979**Return value** 980 981| Type | Description | 982| --------------------------- | --------------------------------- | 983| [DataBlob](#datablob) | Public key data in the specified format.| 984 985**Error codes** 986For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 987 988| ID| Error Message | 989| -------- | ---------------------- | 990| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 991| 17620001 | memory error. | 992| 17630001 | crypto operation error. | 993 994**Example** 995 996<!--code_no_check--> 997```ts 998let key: cryptoFramework.PubKey; // Key is a public key object. The generation process is omitted here. 999let returnBlob = key.getEncodedDer('X509|UNCOMPRESSED'); 1000console.info('returnBlob data: ' + returnBlob.data); 1001``` 1002 1003### getEncodedPem<sup>12+</sup> 1004 1005getEncodedPem(format: string): string 1006 1007Obtains the key data. This API returns the result synchronously. The key can be an RSA public or private key. The public key must comply with the X.509 specifications, PKCS #1 specifications, and PEM encoding format. 1008 1009**Atomic service API**: This API can be used in atomic services since API version 12. 1010 1011**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 1012 1013**Parameters** 1014 1015| Name| Type | Mandatory| Description | 1016| ---- | --------------------- | ---- | -------------------- | 1017| format | string | Yes | Encoding format of the key data to obtain. The format for a public key can be **'PKCS1'** or **'X509'**.| 1018 1019**Return value** 1020 1021| Type | Description | 1022| --------------------------- | --------------------------------- | 1023| string | Key data obtained.| 1024 1025**Error codes** 1026For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 1027 1028| ID| Error Message | 1029| -------- | ---------------------- | 1030| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 1031| 17620001 | memory error. | 1032| 17630001 | crypto operation error. | 1033 1034**Example** 1035 1036```ts 1037import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 1038 1039let publicPkcs1Str1024: string = 1040 "-----BEGIN RSA PUBLIC KEY-----\n" 1041 + "MIGJAoGBALAg3eavbX433pOjGdWdpL7HIr1w1EAeIcaCtuMfDpECPdX6X5ZjrwiE\n" 1042 + "h7cO51WXMT2gyN45DCQySr/8cLE2UiUVHo7qlrSatdLA9ETtgob3sJ4qTaBg5Lxg\n" 1043 + "SHy2gC+bvEpuIuRe64yXGuM/aP+ZvmIj9QBIVI9mJD8jLEOvQBBpAgMBAAE=\n" 1044 + "-----END RSA PUBLIC KEY-----\n"; 1045 1046function TestPubKeyPkcs1ToX509BySync1024() { 1047 let rsaGenerator = cryptoFramework.createAsyKeyGenerator('RSA1024'); 1048 let keyPair = rsaGenerator.convertPemKeySync(publicPkcs1Str1024, null); 1049 let pubPemKey = keyPair.pubKey; 1050 let pubString = pubPemKey.getEncodedPem('X509'); 1051 console.info("[sync]TestPubKeyPkcs1ToX509BySync1024 pubString output is " + pubString); 1052} 1053``` 1054 1055## PriKey 1056 1057Provides APIs for private key operations. **PriKey** is a child class of [Key](#key). It needs to be passed in during asymmetric encryption and decryption, signing, and key agreement. 1058 1059The private key can be generated by using the asymmetric key generator [AsyKeyGenerator](#asykeygenerator) or [AsyKeyGeneratorBySpec](#asykeygeneratorbyspec10). 1060 1061### clearMem 1062 1063clearMem(): void 1064 1065Clears the private keys in the memory. This API returns the result synchronously. 1066 1067**Atomic service API**: This API can be used in atomic services since API version 12. 1068 1069**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 1070 1071The supported system capability is SystemCapability.Security.CryptoFramework in API versions 9 to 11 and SystemCapability.Security.CryptoFramework.Key.AsymKey since API version 12. 1072 1073**Example** 1074 1075<!--code_no_check--> 1076```ts 1077let key: cryptoFramework.PriKey; // The key is a private key generated by the asymmetric key generator. The generation process is omitted here. 1078key.clearMem(); // For the asymmetric private key, clearMem() releases the internal key struct. After clearMem is executed, getEncoded() is not supported. 1079``` 1080 1081### getAsyKeySpec<sup>10+</sup> 1082 1083getAsyKeySpec(itemType: AsyKeySpecItem): bigint | string | number 1084 1085Obtains a key parameter. This API returns the result synchronously. 1086 1087**Atomic service API**: This API can be used in atomic services since API version 12. 1088 1089**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 1090 1091The supported system capability is SystemCapability.Security.CryptoFramework in API versions 10 to 11 and SystemCapability.Security.CryptoFramework.Key.AsymKey since API version 12. 1092 1093**Parameters** 1094 1095| Name| Type | Mandatory| Description | 1096| ---- | --------------------- | ---- | -------------------- | 1097| itemType | [AsyKeySpecItem](#asykeyspecitem10) | Yes | Key parameter to obtain.| 1098 1099**Return value** 1100 1101| Type | Description | 1102| --------------------------- | --------------------------------- | 1103| bigint \| string \| number | Content of the key parameter obtained.| 1104 1105**Error codes** 1106For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 1107 1108| ID| Error Message | 1109| -------- | ---------------------- | 1110| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 1111| 17620001 | memory error. | 1112| 17630001 | crypto operation error. | 1113 1114**Example** 1115 1116<!--code_no_check--> 1117```ts 1118let key: cryptoFramework.PriKey; // key is a private key object. The generation process is omitted here. 1119let p = key.getAsyKeySpec(cryptoFramework.AsyKeySpecItem.ECC_FP_P_BN); 1120console.info('ecc item --- p: ' + p.toString(16)); 1121``` 1122### getEncodedDer<sup>12+</sup> 1123 1124getEncodedDer(format: string): DataBlob 1125 1126Obtains the private key data that complies with the ASN.1 syntax and DER encoding based on the specified format (such as the key specifications). Currently, only the ECC private key data in PKCS #8 format can be obtained. 1127 1128> **NOTE** 1129> 1130> The difference between [Key.getEncoded()](#getencoded) and this API is as follows:<br> 1131> 1. You can specify the format of the key data to be obtained in this API. Currently, the ECC private key data in PKCS #8 format is supported. 1132> 2. The format of the key data to be obtained cannot be specified in [Key.getEncoded()](#getencoded). 1133 1134**Atomic service API**: This API can be used in atomic services since API version 12. 1135 1136**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 1137 1138**Parameters** 1139 1140| Name| Type | Mandatory| Description | 1141| ---- | --------------------- | ---- | -------------------- | 1142| format | string | Yes | Format of the key. Currently, only **PKCS8** is supported.| 1143 1144**Return value** 1145 1146| Type | Description | 1147| --------------------------- | --------------------------------- | 1148| [DataBlob](#datablob) | Private key data of the specified format obtained.| 1149 1150**Error codes** 1151For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 1152 1153| ID| Error Message | 1154| -------- | ---------------------- | 1155| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 1156| 17620001 | memory error. | 1157| 17630001 | crypto operation error. | 1158 1159**Example** 1160 1161<!--code_no_check--> 1162```ts 1163let key: cryptoFramework.PriKey; // key is a private key object. The generation process is omitted here. 1164let returnBlob = key.getEncodedDer('PKCS8'); 1165console.info('returnBlob data: ' + returnBlob.data); 1166``` 1167 1168### getEncodedPem<sup>12+</sup> 1169 1170getEncodedPem(format: string): string 1171 1172Obtains the key data. This API returns the result synchronously. The key can be an RSA public or private key. The private key must comply with PKCS #8 or PKCS #1 specifications and PEM encoding format. 1173 1174**Atomic service API**: This API can be used in atomic services since API version 12. 1175 1176**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 1177 1178**Parameters** 1179 1180| Name| Type | Mandatory| Description | 1181| ---- | --------------------- | ---- | -------------------- | 1182| format | string | Yes | Encoding format of the key data to obtain. The format of a private key can be **PKCS1** or **'PKCS8'**.| 1183 1184**Return value** 1185 1186| Type | Description | 1187| --------------------------- | --------------------------------- | 1188| string | Key data obtained.| 1189 1190**Error codes** 1191For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 1192 1193| ID| Error Message | 1194| -------- | ---------------------- | 1195| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 1196| 17620001 | memory error. | 1197| 17630001 | crypto operation error. | 1198 1199**Example** 1200 1201```ts 1202import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 1203 1204let priKeyPkcs1Str1024: string = 1205 "-----BEGIN RSA PRIVATE KEY-----\n" 1206 + "MIICXQIBAAKBgQCwIN3mr21+N96ToxnVnaS+xyK9cNRAHiHGgrbjHw6RAj3V+l+W\n" 1207 + "Y68IhIe3DudVlzE9oMjeOQwkMkq//HCxNlIlFR6O6pa0mrXSwPRE7YKG97CeKk2g\n" 1208 + "YOS8YEh8toAvm7xKbiLkXuuMlxrjP2j/mb5iI/UASFSPZiQ/IyxDr0AQaQIDAQAB\n" 1209 + "AoGAEvBFzBNa+7J4PXnRQlYEK/tvsd0bBZX33ceacMubHl6WVZbphltLq+fMTBPP\n" 1210 + "LjXmtpC+aJ7Lvmyl+wTi/TsxE9vxW5JnbuRT48rnZ/Xwq0eozDeEeIBRrpsr7Rvr\n" 1211 + "7ctrgzr4m4yMHq9aDgpxj8IR7oHkfwnmWr0wM3FuiVlj650CQQDineeNZ1hUTkj4\n" 1212 + "D3O+iCi3mxEVEeJrpqrmSFolRMb+iozrIRKuJlgcOs+Gqi2fHfOTTL7LkpYe8SVg\n" 1213 + "e3JxUdVLAkEAxvcZXk+byMFoetrnlcMR13VHUpoVeoV9qkv6CAWLlbMdgf7uKmgp\n" 1214 + "a1Yp3QPDNQQqkPvrqtfR19JWZ4uy1qREmwJALTU3BjyBoH/liqb6fh4HkWk75Som\n" 1215 + "MzeSjFIOubSYxhq5tgZpBZjcpvUMhV7Zrw54kwASZ+YcUJvmyvKViAm9NQJBAKF7\n" 1216 + "DyXSKrem8Ws0m1ybM7HQx5As6l3EVhePDmDQT1eyRbKp+xaD74nkJpnwYdB3jyyY\n" 1217 + "qc7A1tj5J5NmeEFolR0CQQCn76Xp8HCjGgLHw9vg7YyIL28y/XyfFyaZAzzK+Yia\n" 1218 + "akNwQ6NeGtXSsuGCcyyfpacHp9xy8qXQNKSkw03/5vDO\n" 1219 + "-----END RSA PRIVATE KEY-----\n"; 1220 1221function TestPriKeyPkcs1ToPkcs8BySync1024() { 1222 let rsaGenerator = cryptoFramework.createAsyKeyGenerator('RSA1024'); 1223 let keyPair = rsaGenerator.convertPemKeySync(null, priKeyPkcs1Str1024); 1224 let priPemKey = keyPair.priKey; 1225 let priString = priPemKey.getEncodedPem('PKCS8'); 1226 console.info("[sync]TestPriKeyPkcs1ToPkcs8BySync1024 priString output is " + priString); 1227} 1228``` 1229 1230### getEncodedPem<sup>18+</sup> 1231 1232getEncodedPem(format: string, config: KeyEncodingConfig): string 1233 1234Obtains the key data. This API returns the result synchronously. The key can be an RSA public or private key. The private key must comply with PKCS #8 or PKCS #1 specifications and PEM encoding format. 1235 1236**Atomic service API**: This API can be used in atomic services since API version 18. 1237 1238**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 1239 1240**Parameters** 1241 1242| Name| Type | Mandatory| Description | 1243| ---- | --------------------- | ---- | -------------------- | 1244| format | string | Yes | Encoding format of the key data to obtain. The format of a private key can be **PKCS1** or **'PKCS8'**.| 1245| config | [KeyEncodingConfig](#keyencodingconfig18) | Yes| Options (including the password and algorithm) for encoding the private key.| 1246 1247**Return value** 1248 1249| Type | Description | 1250| --------------------------- | --------------------------------- | 1251| string | Key data obtained. If **config** is specified, the key obtained is encoded.| 1252 1253**Error codes** 1254For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 1255 1256| ID| Error Message | 1257| -------- | ---------------------- | 1258| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 1259| 17620001 | memory error. | 1260| 17630001 | crypto operation error. | 1261 1262**Example** 1263 1264```ts 1265import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 1266 1267let priKeyPkcs1Str1024: string = 1268 "-----BEGIN RSA PRIVATE KEY-----\n" 1269 + "MIICXQIBAAKBgQCwIN3mr21+N96ToxnVnaS+xyK9cNRAHiHGgrbjHw6RAj3V+l+W\n" 1270 + "Y68IhIe3DudVlzE9oMjeOQwkMkq//HCxNlIlFR6O6pa0mrXSwPRE7YKG97CeKk2g\n" 1271 + "YOS8YEh8toAvm7xKbiLkXuuMlxrjP2j/mb5iI/UASFSPZiQ/IyxDr0AQaQIDAQAB\n" 1272 + "AoGAEvBFzBNa+7J4PXnRQlYEK/tvsd0bBZX33ceacMubHl6WVZbphltLq+fMTBPP\n" 1273 + "LjXmtpC+aJ7Lvmyl+wTi/TsxE9vxW5JnbuRT48rnZ/Xwq0eozDeEeIBRrpsr7Rvr\n" 1274 + "7ctrgzr4m4yMHq9aDgpxj8IR7oHkfwnmWr0wM3FuiVlj650CQQDineeNZ1hUTkj4\n" 1275 + "D3O+iCi3mxEVEeJrpqrmSFolRMb+iozrIRKuJlgcOs+Gqi2fHfOTTL7LkpYe8SVg\n" 1276 + "e3JxUdVLAkEAxvcZXk+byMFoetrnlcMR13VHUpoVeoV9qkv6CAWLlbMdgf7uKmgp\n" 1277 + "a1Yp3QPDNQQqkPvrqtfR19JWZ4uy1qREmwJALTU3BjyBoH/liqb6fh4HkWk75Som\n" 1278 + "MzeSjFIOubSYxhq5tgZpBZjcpvUMhV7Zrw54kwASZ+YcUJvmyvKViAm9NQJBAKF7\n" 1279 + "DyXSKrem8Ws0m1ybM7HQx5As6l3EVhePDmDQT1eyRbKp+xaD74nkJpnwYdB3jyyY\n" 1280 + "qc7A1tj5J5NmeEFolR0CQQCn76Xp8HCjGgLHw9vg7YyIL28y/XyfFyaZAzzK+Yia\n" 1281 + "akNwQ6NeGtXSsuGCcyyfpacHp9xy8qXQNKSkw03/5vDO\n" 1282 + "-----END RSA PRIVATE KEY-----\n"; 1283 1284function TestPriKeyPkcs1Encoded() { 1285 let rsaGenerator = cryptoFramework.createAsyKeyGenerator('RSA1024'); 1286 let keyPair = rsaGenerator.convertPemKeySync(null, priKeyPkcs1Str1024); 1287 let options : cryptoFramework.KeyEncodingConfig = { 1288 password: "123456", 1289 cipherName: "AES-128-CBC" 1290 } 1291 let priPemKey = keyPair.priKey; 1292 let priString = priPemKey.getEncodedPem('PKCS1', options); 1293 console.info("[sync]TestPriKeyPkcs1Encoded priString output is " + priString); 1294} 1295``` 1296 1297## KeyPair 1298 1299Defines an asymmetric key pair, which includes a public key and a private key. 1300 1301The asymmetric key pair can be generated by using the asymmetric key generator [AsyKeyGenerator](#asykeygenerator) or [AsyKeyGeneratorBySpec](#asykeygeneratorbyspec10). 1302 1303> **NOTE** 1304> 1305> 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. 1306> 1307> The service must reference the **KeyPair** object instead of the internal **pubKey** or **priKey** object. 1308 1309### Attributes 1310 1311**Atomic service API**: This API can be used in atomic services since API version 12. 1312 1313**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 1314 1315The supported system capability is SystemCapability.Security.CryptoFramework in API versions 9 to 11 and SystemCapability.Security.CryptoFramework.Key.AsymKey since API version 12. 1316 1317| Name | Type | Readable| Writable| Description | 1318| ------- | ------ | ---- | ---- | ------------ | 1319| priKey | [PriKey](#prikey) | Yes | No | Private key. | 1320| pubKey | [PubKey](#pubkey) | Yes | No | Public key. | 1321 1322## cryptoFramework.createSymKeyGenerator 1323 1324createSymKeyGenerator(algName: string): SymKeyGenerator 1325 1326Creates a **symKeyGenerator** instance based on the specified algorithm. 1327 1328For details about the supported specifications, see [Symmetric Key Generation and Conversion Specifications](../../security/CryptoArchitectureKit/crypto-sym-key-generation-conversion-spec.md). 1329 1330**Atomic service API**: This API can be used in atomic services since API version 12. 1331 1332**System capability**: SystemCapability.Security.CryptoFramework.Key.SymKey 1333 1334The supported system capability is SystemCapability.Security.CryptoFramework in API versions 9 to 11 and SystemCapability.Security.CryptoFramework.Key.SymKey since API version 12. 1335 1336**Parameters** 1337 1338| Name | Type | Mandatory| Description | 1339| ------- | ------ | ---- | ------------------------------------------------------------ | 1340| algName | string | Yes | Algorithm used to create the **symKeyGenerator** instance.<br>For details, see **String Parameter** in [Symmetric Key Generation and Conversion Specifications](../../security/CryptoArchitectureKit/crypto-sym-key-generation-conversion-spec.md).| 1341 1342**Return value** 1343 1344| Type | Description | 1345| ----------------------------------- | -------------------------- | 1346| [SymKeyGenerator](#symkeygenerator) | **symKeyGenerator** instance created.| 1347 1348**Error codes** 1349For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 1350 1351| ID| Error Message | 1352| -------- | ---------------------- | 1353| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 1354| 801 | this operation is not supported. | 1355 1356**Example** 1357 1358```ts 1359import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 1360 1361let symKeyGenerator = cryptoFramework.createSymKeyGenerator('3DES192'); 1362``` 1363 1364## SymKeyGenerator 1365 1366Provides APIs for using the **symKeyGenerator**. 1367 1368Before using any API of the **SymKeyGenerator** class, you must create a **SymKeyGenerator** instance by using [createSymKeyGenerator](#cryptoframeworkcreatesymkeygenerator). 1369 1370### Attributes 1371 1372**Atomic service API**: This API can be used in atomic services since API version 12. 1373 1374**System capability**: SystemCapability.Security.CryptoFramework.Key.SymKey 1375 1376The supported system capability is SystemCapability.Security.CryptoFramework in API versions 9 to 11 and SystemCapability.Security.CryptoFramework.Key.SymKey since API version 12. 1377 1378| Name | Type | Readable| Writable| Description | 1379| ------- | ------ | ---- | ---- | ------------------------------ | 1380| algName | string | Yes | No | Algorithm used by the **symKeyGenerator**.| 1381 1382### generateSymKey 1383 1384generateSymKey(callback: AsyncCallback\<SymKey>): void 1385 1386Generates a key randomly. This API uses an asynchronous callback to return the result. 1387 1388This API can be used only after a **symKeyGenerator** instance is created by using [createSymKeyGenerator](#cryptoframeworkcreatesymkeygenerator). 1389 1390**RAND_priv_bytes()** of OpenSSL can be used to generate random keys. 1391 1392> **NOTE** 1393> 1394> For the symmetric key used with the HMAC algorithm, if the hash algorithm (for example, **HMAC|SHA256**) is specified when the symmetric key generator is created, a binary key with the same length as the hash value will be randomly generated. For example, if **HMAC|SHA256** is specified, a 256-bit key will be randomly generated.<br>If no hash algorithm is specified when the symmetric key generator is created (for example, only HMAC is specified), symmetric key data cannot be randomly generated. In this case, you can use [convertKey](#convertkey) to generate symmetric key data. 1395 1396**Atomic service API**: This API can be used in atomic services since API version 12. 1397 1398**System capability**: SystemCapability.Security.CryptoFramework.Key.SymKey 1399 1400The supported system capability is SystemCapability.Security.CryptoFramework in API versions 9 to 11 and SystemCapability.Security.CryptoFramework.Key.SymKey since API version 12. 1401 1402**Parameters** 1403 1404| Name | Type | Mandatory| Description | 1405| -------- | --------------------------------- | ---- | ------------------------------------------------------------ | 1406| 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.| 1407 1408**Error codes** 1409For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 1410 1411| ID| Error Message | 1412| -------- | ------------- | 1413| 17620001 | memory error. | 1414 1415**Example** 1416 1417```ts 1418import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 1419 1420let symKeyGenerator = cryptoFramework.createSymKeyGenerator('3DES192'); 1421 symKeyGenerator.generateSymKey((err, symKey) => { 1422 console.info('Generate symKey success, algName: ' + symKey.algName); 1423 }); 1424``` 1425 1426### generateSymKey 1427 1428generateSymKey(): Promise\<SymKey> 1429 1430Generates a key randomly. This API uses a promise to return the result. 1431 1432This API can be used only after a **symKeyGenerator** instance is created by using [createSymKeyGenerator](#cryptoframeworkcreatesymkeygenerator). 1433 1434**RAND_priv_bytes()** of OpenSSL can be used to generate random keys. 1435 1436**Atomic service API**: This API can be used in atomic services since API version 12. 1437 1438**System capability**: SystemCapability.Security.CryptoFramework.Key.SymKey 1439 1440The supported system capability is SystemCapability.Security.CryptoFramework in API versions 9 to 11 and SystemCapability.Security.CryptoFramework.Key.SymKey since API version 12. 1441 1442**Return value** 1443 1444| Type | Description | 1445| --------------------------- | --------------------------------- | 1446| Promise\<[SymKey](#symkey)> | Promise used to return the symmetric key generated.| 1447 1448**Error codes** 1449For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 1450 1451| ID| Error Message | 1452| -------- | ------------- | 1453| 17620001 | memory error. | 1454 1455**Example** 1456 1457```ts 1458import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 1459import { BusinessError } from '@kit.BasicServicesKit'; 1460 1461let symKeyGenerator = cryptoFramework.createSymKeyGenerator('AES128'); 1462 symKeyGenerator.generateSymKey() 1463 .then(symKey => { 1464 console.info('Generate symKey success, algName: ' + symKey.algName); 1465 }).catch((error: BusinessError) => { 1466 console.error(`Generate symKey failed, ${error.code}, ${error.message}`); 1467 }); 1468``` 1469 1470### generateSymKeySync<sup>12+</sup> 1471 1472generateSymKeySync(): SymKey 1473 1474Generates a symmetric key randomly. This API returns the result synchronously. 1475 1476This API can be used only after a **symKeyGenerator** instance is created by using [createSymKeyGenerator](#cryptoframeworkcreatesymkeygenerator). 1477 1478**RAND_priv_bytes()** of OpenSSL can be used to generate random keys. 1479 1480> **NOTE** 1481> 1482> For the symmetric key used with the HMAC algorithm, if the hash algorithm (for example, **HMAC|SHA256**) is specified when the symmetric key generator is created, a binary key with the same length as the hash value will be randomly generated. For example, if **HMAC|SHA256** is specified, a 256-bit key will be randomly generated.<br>If no hash algorithm is specified when the symmetric key generator is created (for example, only **HMAC** is specified), symmetric key data cannot be randomly generated. In this case, you can use [convertKeySync](#convertkeysync12) to generate symmetric key data. 1483 1484**Atomic service API**: This API can be used in atomic services since API version 12. 1485 1486**System capability**: SystemCapability.Security.CryptoFramework.Key.SymKey 1487 1488**Error codes** 1489For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 1490 1491| ID| Error Message | 1492| -------- | ------------- | 1493| 17620001 | memory error. | 1494 1495**Example** 1496 1497```ts 1498import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 1499 1500function testGenerateSymKeySync() { 1501 // Create a SymKeyGenerator instance. 1502 let symKeyGenerator = cryptoFramework.createSymKeyGenerator('AES256'); 1503 // Use SymKeyGenerator to randomly generate a symmetric key. 1504 let key = symKeyGenerator.generateSymKeySync(); 1505 let encodedKey = key.getEncoded(); 1506 console.info('key hex:' + encodedKey.data); 1507} 1508``` 1509 1510### convertKey 1511 1512convertKey(key: DataBlob, callback: AsyncCallback\<SymKey>): void 1513 1514Converts data into a symmetric key. This API uses an asynchronous callback to return the result. 1515 1516This API can be used only after a **symKeyGenerator** instance is created by using [createSymKeyGenerator](#cryptoframeworkcreatesymkeygenerator). 1517 1518> **NOTE** 1519> 1520> For the symmetric key used with the HMAC algorithm, if the hash algorithm (for example, **HMAC|SHA256**) is specified when the symmetric key generator is created, the binary key data to be passed in must be of the same length as the hash. For example, if **HMAC|SHA256** is specified, a 256-bit key must be passed in.<br>If no hash algorithm is specified when the symmetric key generator is created (for example, only HMAC is specified), the length of the binary key data is in the range of [1,4096], in bytes. 1521 1522**Atomic service API**: This API can be used in atomic services since API version 12. 1523 1524**System capability**: SystemCapability.Security.CryptoFramework.Key.SymKey 1525 1526The supported system capability is SystemCapability.Security.CryptoFramework in API versions 9 to 11 and SystemCapability.Security.CryptoFramework.Key.SymKey since API version 12. 1527 1528**Parameters** 1529 1530| Name | Type | Mandatory| Description | 1531| -------- | ------------------- | ---- | ---------------------| 1532| key | [DataBlob](#datablob) | Yes | Data to convert. | 1533| 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.| 1534 1535**Error codes** 1536For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 1537 1538| ID| Error Message | 1539| -------- | --------------------------------------------------- | 1540| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 1541| 17620001 | memory error. | 1542 1543**Example** 1544 1545```ts 1546import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 1547 1548function genKeyMaterialBlob(): cryptoFramework.DataBlob { 1549 let arr = [ 1550 0xba, 0x3d, 0xc2, 0x71, 0x21, 0x1e, 0x30, 0x56, 1551 0xad, 0x47, 0xfc, 0x5a, 0x46, 0x39, 0xee, 0x7c, 1552 0xba, 0x3b, 0xc2, 0x71, 0xab, 0xa0, 0x30, 0x72]; // keyLen = 192 (24 bytes) 1553 let keyMaterial = new Uint8Array(arr); 1554 return { data: keyMaterial }; 1555} 1556 1557function testConvertKey() { 1558 let symKeyGenerator = cryptoFramework.createSymKeyGenerator('3DES192'); 1559 let keyMaterialBlob = genKeyMaterialBlob(); 1560 symKeyGenerator.convertKey(keyMaterialBlob, (err, symKey) => { 1561 console.info('Convert symKey success, algName: ' + symKey.algName); 1562 }); 1563} 1564``` 1565 1566### convertKey 1567 1568convertKey(key: DataBlob): Promise\<SymKey> 1569 1570Converts data into a symmetric key. This API uses a promise to return the result. 1571 1572This API can be used only after a **symKeyGenerator** instance is created by using [createSymKeyGenerator](#cryptoframeworkcreatesymkeygenerator). 1573 1574**Atomic service API**: This API can be used in atomic services since API version 12. 1575 1576**System capability**: SystemCapability.Security.CryptoFramework.Key.SymKey 1577 1578The supported system capability is SystemCapability.Security.CryptoFramework in API versions 9 to 11 and SystemCapability.Security.CryptoFramework.Key.SymKey since API version 12. 1579 1580**Parameters** 1581 1582| Name| Type | Mandatory| Description | 1583| ---- | --------------------- | ---- | -------------------- | 1584| key | [DataBlob](#datablob) | Yes | Data to convert.| 1585 1586**Return value** 1587 1588| Type | Description | 1589| --------------------------- | --------------------------------- | 1590| Promise\<[SymKey](#symkey)> | Promise used to return the symmetric key generated.| 1591 1592**Error codes** 1593For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 1594 1595| ID| Error Message | 1596| -------- | --------------------------------------------- | 1597| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 1598| 17620001 | memory error. | 1599 1600**Example** 1601 1602```ts 1603import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 1604import { BusinessError } from '@kit.BasicServicesKit'; 1605 1606function genKeyMaterialBlob(): cryptoFramework.DataBlob { 1607 let arr = [ 1608 0xba, 0x3d, 0xc2, 0x71, 0x21, 0x1e, 0x30, 0x56, 1609 0xad, 0x47, 0xfc, 0x5a, 0x46, 0x39, 0xee, 0x7c, 1610 0xba, 0x3b, 0xc2, 0x71, 0xab, 0xa0, 0x30, 0x72]; // keyLen = 192 (24 bytes) 1611 let keyMaterial = new Uint8Array(arr); 1612 return { data: keyMaterial }; 1613} 1614 1615function testConvertKey() { 1616 let symKeyGenerator = cryptoFramework.createSymKeyGenerator('3DES192'); 1617 let keyMaterialBlob = genKeyMaterialBlob(); 1618 symKeyGenerator.convertKey(keyMaterialBlob) 1619 .then(symKey => { 1620 console.info('Convert symKey success, algName: ' + symKey.algName); 1621 }).catch((error: BusinessError) => { 1622 console.error(`Convert symKey failed, ${error.code}, ${error.message}`); 1623 }); 1624} 1625``` 1626 1627### convertKeySync<sup>12+</sup> 1628 1629convertKeySync(key: DataBlob): SymKey 1630 1631Converts data into a symmetric key. This API returns the result synchronously. 1632 1633This API can be used only after a **symKeyGenerator** instance is created by using [createSymKeyGenerator](#cryptoframeworkcreatesymkeygenerator). 1634 1635> **NOTE** 1636> 1637> For the symmetric key used with the HMAC algorithm, if the hash algorithm (for example, **HMAC|SHA256**) is specified when the symmetric key generator is created, the binary key data to be passed in must be of the same length as the hash. For example, if **HMAC|SHA256** is specified, a 256-bit key must be passed in.<br>If no hash algorithm is specified when the symmetric key generator is created (for example, only HMAC is specified), the length of the binary key data is in the range of [1,4096], in bytes. 1638 1639**Atomic service API**: This API can be used in atomic services since API version 12. 1640 1641**System capability**: SystemCapability.Security.CryptoFramework.Key.SymKey 1642 1643**Parameters** 1644 1645| Name | Type | Mandatory| Description | 1646| -------- | ------------------- | ---- | ---------------------| 1647| key | [DataBlob](#datablob) | Yes | Data to convert. | 1648 1649**Error codes** 1650For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 1651 1652| ID| Error Message | 1653| -------- | --------------------------------------------------- | 1654| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 1655| 17620001 | memory error. | 1656 1657**Example** 1658 1659```ts 1660import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 1661import { buffer } from '@kit.ArkTS'; 1662 1663function testConvertKeySync() { 1664 // The symmetric key length is 64 bytes (512 bits). 1665 let keyMessage = '87654321abcdefgh87654321abcdefgh87654321abcdefgh87654321abcdefgh'; 1666 let keyBlob: cryptoFramework.DataBlob = { 1667 data : new Uint8Array(buffer.from(keyMessage, 'utf-8').buffer) 1668 } 1669 let symKeyGenerator = cryptoFramework.createSymKeyGenerator('HMAC'); 1670 let key = symKeyGenerator.convertKeySync(keyBlob); 1671 let encodedKey = key.getEncoded(); 1672 console.info('key encoded data: ' + encodedKey.data); 1673} 1674``` 1675 1676## cryptoFramework.createAsyKeyGenerator 1677 1678createAsyKeyGenerator(algName: string): AsyKeyGenerator 1679 1680Creates an **AsyKeyGenerator** instance based on the specified algorithm. 1681 1682For details about the supported specifications, see [Asymmetric Key Generation and Conversion Specifications](../../security/CryptoArchitectureKit/crypto-asym-key-generation-conversion-spec.md). 1683 1684**Atomic service API**: This API can be used in atomic services since API version 12. 1685 1686**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 1687 1688The supported system capability is SystemCapability.Security.CryptoFramework in API versions 9 to 11 and SystemCapability.Security.CryptoFramework.Key.AsymKey since API version 12. 1689 1690**Parameters** 1691 1692| Name | Type | Mandatory| Description | 1693| ------- | ------ | ---- | -------------------------------- | 1694| algName | string | Yes | [Algorithm used to create the **symkeyGenerator**](../../security/CryptoArchitectureKit/crypto-asym-key-generation-conversion-spec.md)| 1695 1696**Return value** 1697 1698| Type | Description | 1699| --------------- | ---------------------------- | 1700| [AsyKeyGenerator](#asykeygenerator) | **AsyKeyGenerator** instance created.| 1701 1702**Error codes** 1703For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 1704 1705| ID| Error Message | 1706| -------- | ---------------------- | 1707| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 1708| 801 | this operation is not supported. | 1709| 17620001 | memory error. | 1710 1711**Example** 1712 1713```ts 1714import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 1715 1716let asyKeyGenerator = cryptoFramework.createAsyKeyGenerator('ECC256'); 1717``` 1718 1719## AsyKeyGenerator 1720 1721Provides APIs for using the **AsKeyGenerator**. Before using any API of the **AsKeyGenerator** class, you must create an **AsyKeyGenerator** instance by using **createAsyKeyGenerator()**. 1722 1723### Attributes 1724 1725**Atomic service API**: This API can be used in atomic services since API version 12. 1726 1727**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 1728 1729The supported system capability is SystemCapability.Security.CryptoFramework in API versions 9 to 11 and SystemCapability.Security.CryptoFramework.Key.AsymKey since API version 12. 1730 1731| Name | Type | Readable| Writable| Description | 1732| ------- | ------ | ---- | ---- | -------------------------------- | 1733| algName | string | Yes | No | Algorithm used by the **AsKeyGenerator**.| 1734 1735### generateKeyPair 1736 1737generateKeyPair(callback: AsyncCallback\<KeyPair>): void 1738 1739Generates a key pair randomly. This API uses an asynchronous callback to return the result. 1740 1741**Atomic service API**: This API can be used in atomic services since API version 12. 1742 1743**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 1744 1745The supported system capability is SystemCapability.Security.CryptoFramework in API versions 9 to 11 and SystemCapability.Security.CryptoFramework.Key.AsymKey since API version 12. 1746 1747**Parameters** 1748 1749| Name | Type | Mandatory| Description | 1750| -------- | ----------------------- | ---- | ------------------------------ | 1751| callback | AsyncCallback\<[KeyPair](#keypair)> | Yes | Callback invoked to return the key pair obtained.| 1752 1753**Error codes** 1754For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 1755 1756| ID| Error Message | 1757| -------- | ---------------------- | 1758| 401 | invalid parameters. Possible causes: <br>Incorrect parameter types;| 1759| 17620001 | memory error. | 1760| 17630001 | crypto operation error. | 1761 1762**Example** 1763 1764```ts 1765import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 1766 1767let asyKeyGenerator = cryptoFramework.createAsyKeyGenerator('ECC256'); 1768asyKeyGenerator.generateKeyPair((err, keyPair) => { 1769 if (err) { 1770 console.error("generateKeyPair: error."); 1771 return; 1772 } 1773 console.info('generateKeyPair: success.'); 1774}) 1775``` 1776 1777### generateKeyPair 1778 1779generateKeyPair(): Promise\<KeyPair> 1780 1781Generates a key pair randomly. This API uses a promise to return the result. 1782 1783**Atomic service API**: This API can be used in atomic services since API version 12. 1784 1785**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 1786 1787The supported system capability is SystemCapability.Security.CryptoFramework in API versions 9 to 11 and SystemCapability.Security.CryptoFramework.Key.AsymKey since API version 12. 1788 1789**Return value** 1790 1791| Type | Description | 1792| ----------------- | --------------------------------- | 1793| Promise\<[KeyPair](#keypair)> | Promise used to return the key pair generated.| 1794 1795**Error codes** 1796For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 1797 1798| ID| Error Message | 1799| -------- | ---------------------- | 1800| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed. | 1801| 17620001 | memory error. | 1802| 17630001 | crypto operation error. | 1803 1804**Example** 1805 1806```ts 1807import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 1808import { BusinessError } from '@kit.BasicServicesKit'; 1809 1810let asyKeyGenerator = cryptoFramework.createAsyKeyGenerator('ECC256'); 1811let keyGenPromise = asyKeyGenerator.generateKeyPair(); 1812keyGenPromise.then(keyPair => { 1813 console.info('generateKeyPair success.'); 1814}).catch((error: BusinessError) => { 1815 console.error("generateKeyPair error."); 1816}); 1817``` 1818 1819### generateKeyPairSync<sup>12+</sup> 1820 1821generateKeyPairSync(): KeyPair 1822 1823Generates a key pair randomly. This API returns the result synchronously. 1824 1825**Atomic service API**: This API can be used in atomic services since API version 12. 1826 1827**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 1828 1829**Return value** 1830 1831| Type | Description | 1832| ----------------- | --------------------------------- | 1833| [KeyPair](#keypair) | Asymmetric key pair generated.| 1834 1835**Error codes** 1836For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 1837 1838| ID| Error Message | 1839| -------- | ---------------------- | 1840| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed. | 1841| 17620001 | memory error. | 1842| 17630001 | crypto operation error. | 1843 1844**Example** 1845 1846```ts 1847import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 1848 1849let asyKeyGenerator = cryptoFramework.createAsyKeyGenerator('ECC256'); 1850try { 1851 let keyPairData = asyKeyGenerator.generateKeyPairSync(); 1852 if (keyPairData != null) { 1853 console.info('[Sync]: key pair success'); 1854 } else { 1855 console.error("[Sync]: get key pair result fail!"); 1856 } 1857} catch (e) { 1858 console.error(`sync error, ${e.code}, ${e.message}`); 1859} 1860``` 1861 1862### convertKey 1863 1864convertKey(pubKey: DataBlob | null, priKey: DataBlob | null, callback: AsyncCallback\<KeyPair\>): void 1865 1866Converts data into an asymmetric key. This API uses an asynchronous callback to return the result. For details, see **Key Conversion**. 1867 1868**Atomic service API**: This API can be used in atomic services since API version 12. 1869 1870**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 1871 1872The supported system capability is SystemCapability.Security.CryptoFramework in API versions 9 to 11 and SystemCapability.Security.CryptoFramework.Key.AsymKey since API version 12. 1873 1874**Parameters** 1875 1876| Name | Type | Mandatory| Description | 1877| -------- | ----------- | ---- | ------------------------------ | 1878| 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. | 1879| 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. | 1880| callback | AsyncCallback\<[KeyPair](#keypair)> | Yes | Callback invoked to return the key pair obtained.| 1881 1882**Error codes** 1883For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 1884 1885| ID| Error Message | 1886| -------- | ---------------------- | 1887| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 1888| 17620001 | memory error. | 1889| 17630001 | crypto operation error. | 1890 1891**Example** 1892 1893```ts 1894import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 1895 1896let 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]); 1897let 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]); 1898let pubKeyBlob: cryptoFramework.DataBlob = { data: pubKeyArray }; // Binary data of the public key. 1899let priKeyBlob: cryptoFramework.DataBlob = { data: priKeyArray }; // Binary data of the private key. 1900let asyKeyGenerator = cryptoFramework.createAsyKeyGenerator('ECC256'); 1901asyKeyGenerator.convertKey(pubKeyBlob, priKeyBlob, (err, keyPair) => { 1902 if (err) { 1903 console.error("convertKey: error."); 1904 return; 1905 } 1906 console.info('convertKey: success.'); 1907}); 1908``` 1909 1910### convertKey 1911 1912convertKey(pubKey: DataBlob | null, priKey: DataBlob | null): Promise\<KeyPair> 1913 1914Converts data into an asymmetric key. This API uses a promise to return the result. For details, see **Key Conversion**. 1915 1916**Atomic service API**: This API can be used in atomic services since API version 12. 1917 1918**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 1919 1920The supported system capability is SystemCapability.Security.CryptoFramework in API versions 9 to 11 and SystemCapability.Security.CryptoFramework.Key.AsymKey since API version 12. 1921 1922**Parameters** 1923 1924| Name | Type | Mandatory| Description | 1925| ------ | -------- | ---- | ---------------- | 1926| 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.| 1927| 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.| 1928 1929**Return value** 1930 1931| Type | Description | 1932| ----------------- | --------------------------------- | 1933| Promise\<[KeyPair](#keypair)> | Promise used to return the key pair generated.| 1934 1935**Error codes** 1936For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 1937 1938| ID| Error Message | 1939| -------- | ---------------------- | 1940| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 1941| 17620001 | memory error. | 1942| 17630001 | crypto operation error. | 1943 1944**Example** 1945 1946```ts 1947import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 1948import { BusinessError } from '@kit.BasicServicesKit'; 1949 1950let 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]); 1951let 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]); 1952let pubKeyBlob: cryptoFramework.DataBlob = { data: pubKeyArray }; // Binary data of the public key. 1953let priKeyBlob: cryptoFramework.DataBlob = { data: priKeyArray }; // Binary data of the private key. 1954let asyKeyGenerator = cryptoFramework.createAsyKeyGenerator('ECC256'); 1955let keyGenPromise = asyKeyGenerator.convertKey(pubKeyBlob, priKeyBlob); 1956keyGenPromise.then(keyPair => { 1957 console.info('convertKey success.'); 1958}).catch((error: BusinessError) => { 1959 console.error("convertKey error."); 1960}); 1961``` 1962 1963### convertKeySync<sup>12+</sup> 1964 1965convertKeySync(pubKey: DataBlob | null, priKey: DataBlob | null): KeyPair 1966 1967Converts data into an asymmetric key pair. This API returns the result synchronously. For details, see **Key Conversion**. 1968 1969**Atomic service API**: This API can be used in atomic services since API version 12. 1970 1971**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 1972 1973**Parameters** 1974 1975| Name | Type | Mandatory| Description | 1976| ------ | -------- | ---- | ---------------- | 1977| 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.| 1978| 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.| 1979 1980**Return value** 1981 1982| Type | Description | 1983| ----------------- | --------------------------------- | 1984| [KeyPair](#keypair) | Asymmetric key pair generated.| 1985 1986**Error codes** 1987For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 1988 1989| ID| Error Message | 1990| -------- | ---------------------- | 1991| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 1992| 17620001 | memory error. | 1993| 17630001 | crypto operation error. | 1994 1995**Example** 1996 1997```ts 1998import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 1999 2000let 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]); 2001let 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]); 2002let pubKeyBlob: cryptoFramework.DataBlob = { data: pubKeyArray }; // Binary data of the public key. 2003let priKeyBlob: cryptoFramework.DataBlob = { data: priKeyArray }; // Binary data of the private key. 2004let asyKeyGenerator = cryptoFramework.createAsyKeyGenerator('ECC256'); 2005try { 2006 let keyPairData = asyKeyGenerator.convertKeySync(pubKeyBlob, priKeyBlob); 2007 if (keyPairData != null) { 2008 console.info('[Sync]: key pair success'); 2009 } else { 2010 console.error("[Sync]: convert key pair result fail!"); 2011 } 2012} catch (e) { 2013 console.error(`sync error, ${e.code}, ${e.message}`); 2014} 2015``` 2016 2017**Key Conversion** 2018 20191. When **getEncoded()** is used to convert an asymmetric key pair (RSA, ECC, or DSA) into binary data, the public key returned is in X.509 format, and the private key is in PKCS #8 format. For an ECC private key, it is in the format defined in RFC 5915. These key data can be transferred across applications and stored persistently. 20202. When **convertKey()** is used to convert binary data into an asymmetric key object defined by the Crypto framework, the public key 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. 20213. 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. 20224. When **convertKey** or **convertKeySync** is used, the system does not verify whether the specifications of the generated key object are the same as the key specifications specified for the asymmetric key generator. 2023 2024### convertPemKey<sup>12+</sup> 2025 2026convertPemKey(pubKey: string | null, priKey: string | null): Promise\<KeyPair> 2027 2028Converts data into an asymmetric key. This API uses a promise to return the result. 2029 2030> **NOTE** 2031> 1. When **convertPemKey()** is used to convert an external string into an asymmetric key object defined by the Crypto framework, the public key must comply with the ASN.1 syntax, X.509 specifications, and PEM encoding format, and the private key must comply with the ASN.1 syntax, PKCS #8 specifications, and PEM encoding format. 2032> 2. In **convertPemKey()**, 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. 2033> 3. When **convertPemKey** is used to convert an external string into an asymmetric key object defined by the Crypto framework, the system does not verify whether the specifications of the generated key object are the same as the key specifications specified for the asymmetric key generator. 2034 2035**Atomic service API**: This API can be used in atomic services since API version 12. 2036 2037**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 2038 2039**Parameters** 2040 2041| Name | Type | Mandatory| Description | 2042| ------ | -------- | ---- | ---------------- | 2043| pubKey | string \| null | Yes | Public key material to convert. If no public key is required, set this parameter to **null**.| 2044| priKey | string \| null | Yes | Private key material to convert. If no private key is required, set this parameter to **null**. <br>**NOTE**: **pubKey** and **priKey** cannot be **null** at the same time.| 2045 2046**Return value** 2047 2048| Type | Description | 2049| ----------------- | --------------------------------- | 2050| Promise\<[KeyPair](#keypair)> | Promise used to return the key pair generated.| 2051 2052**Error codes** 2053For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 2054 2055| ID| Error Message | 2056| -------- | ---------------------- | 2057| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed. | 2058| 17620001 | memory error. | 2059| 17630001 | crypto operation error. | 2060 2061**Example** 2062 2063```ts 2064import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 2065import { BusinessError } from '@kit.BasicServicesKit'; 2066 2067let priKeyPkcs1Str1024: string = 2068 "-----BEGIN RSA PRIVATE KEY-----\n" 2069 + "MIICXQIBAAKBgQCwIN3mr21+N96ToxnVnaS+xyK9cNRAHiHGgrbjHw6RAj3V+l+W\n" 2070 + "Y68IhIe3DudVlzE9oMjeOQwkMkq//HCxNlIlFR6O6pa0mrXSwPRE7YKG97CeKk2g\n" 2071 + "YOS8YEh8toAvm7xKbiLkXuuMlxrjP2j/mb5iI/UASFSPZiQ/IyxDr0AQaQIDAQAB\n" 2072 + "AoGAEvBFzBNa+7J4PXnRQlYEK/tvsd0bBZX33ceacMubHl6WVZbphltLq+fMTBPP\n" 2073 + "LjXmtpC+aJ7Lvmyl+wTi/TsxE9vxW5JnbuRT48rnZ/Xwq0eozDeEeIBRrpsr7Rvr\n" 2074 + "7ctrgzr4m4yMHq9aDgpxj8IR7oHkfwnmWr0wM3FuiVlj650CQQDineeNZ1hUTkj4\n" 2075 + "D3O+iCi3mxEVEeJrpqrmSFolRMb+iozrIRKuJlgcOs+Gqi2fHfOTTL7LkpYe8SVg\n" 2076 + "e3JxUdVLAkEAxvcZXk+byMFoetrnlcMR13VHUpoVeoV9qkv6CAWLlbMdgf7uKmgp\n" 2077 + "a1Yp3QPDNQQqkPvrqtfR19JWZ4uy1qREmwJALTU3BjyBoH/liqb6fh4HkWk75Som\n" 2078 + "MzeSjFIOubSYxhq5tgZpBZjcpvUMhV7Zrw54kwASZ+YcUJvmyvKViAm9NQJBAKF7\n" 2079 + "DyXSKrem8Ws0m1ybM7HQx5As6l3EVhePDmDQT1eyRbKp+xaD74nkJpnwYdB3jyyY\n" 2080 + "qc7A1tj5J5NmeEFolR0CQQCn76Xp8HCjGgLHw9vg7YyIL28y/XyfFyaZAzzK+Yia\n" 2081 + "akNwQ6NeGtXSsuGCcyyfpacHp9xy8qXQNKSkw03/5vDO\n" 2082 + "-----END RSA PRIVATE KEY-----\n"; 2083let publicPkcs1Str1024: string = 2084 "-----BEGIN RSA PUBLIC KEY-----\n" 2085 + "MIGJAoGBALAg3eavbX433pOjGdWdpL7HIr1w1EAeIcaCtuMfDpECPdX6X5ZjrwiE\n" 2086 + "h7cO51WXMT2gyN45DCQySr/8cLE2UiUVHo7qlrSatdLA9ETtgob3sJ4qTaBg5Lxg\n" 2087 + "SHy2gC+bvEpuIuRe64yXGuM/aP+ZvmIj9QBIVI9mJD8jLEOvQBBpAgMBAAE=\n" 2088 + "-----END RSA PUBLIC KEY-----\n"; 2089async function TestConvertPemKeyByPromise() { 2090 let asyKeyGenerator = cryptoFramework.createAsyKeyGenerator('RSA1024'); 2091 asyKeyGenerator.convertPemKey(publicPkcs1Str1024, priKeyPkcs1Str1024) 2092 .then(keyPair => { 2093 console.info('convertPemKey success.'); 2094 }).catch((error: BusinessError) => { 2095 console.error("convertPemKey error."); 2096 }); 2097} 2098``` 2099 2100### convertPemKey<sup>18+</sup> 2101 2102convertPemKey(pubKey: string | null, priKey: string | null, password: string): Promise\<KeyPair> 2103 2104Converts data into an asymmetric key. This API uses a promise to return the result. 2105 2106> **NOTE** 2107> 1. When **convertPemKey()** is used to convert an external string into an asymmetric key object defined by the Crypto framework, the public key must comply with the ASN.1 syntax, X.509 specifications, and PEM encoding format, and the private key must comply with the ASN.1 syntax, PKCS #8 specifications, and PEM encoding format. 2108> 2. In **convertPemKey()**, 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. 2109> 3. When **convertPemKey** is used to convert an external string into an asymmetric key object defined by the Crypto framework, the system does not verify whether the specifications of the generated key object are the same as the key specifications specified for the asymmetric key generator. 2110> 4. If **password** is passed in, it can be used to decrypt the encrypted private key. 2111 2112**Atomic service API**: This API can be used in atomic services since API version 18. 2113 2114**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 2115 2116**Parameters** 2117 2118| Name | Type | Mandatory| Description | 2119| ------ | -------- | ---- | ---------------- | 2120| pubKey | string \| null | Yes | Public key material to convert. If no public key is required, set this parameter to **null**.| 2121| priKey | string \| null | Yes | Private key material to convert. If no private key is required, set this parameter to **null**. <br>**NOTE**: **pubKey** and **priKey** cannot be **null** at the same time.| 2122| password | string | Yes| Password used to decrypt the private key.| 2123 2124**Return value** 2125 2126| Type | Description | 2127| ----------------- | --------------------------------- | 2128| Promise\<[KeyPair](#keypair)> | Promise used to return the key pair generated.| 2129 2130**Error codes** 2131For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 2132 2133| ID| Error Message | 2134| -------- | ---------------------- | 2135| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed. | 2136| 17620001 | memory error. | 2137| 17630001 | crypto operation error. | 2138 2139**Example** 2140 2141```ts 2142import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 2143import { BusinessError } from '@kit.BasicServicesKit'; 2144 2145let priKeyPkcs1EncodingStr : string = 2146 "-----BEGIN RSA PRIVATE KEY-----\n" 2147 +"Proc-Type: 4,ENCRYPTED\n" 2148 +"DEK-Info: AES-128-CBC,815A066131BF05CF87CE610A59CC69AE\n\n" 2149 +"7Jd0vmOmYGFZ2yRY8fqRl3+6rQlFtNcMILvcb5KWHDSrxA0ULmJE7CW0DSRikHoA\n" 2150 +"t0KgafhYXeQXh0dRy9lvVRAFSLHCLJVjchx90V7ZSivBFEq7+iTozVp4AlbgYsJP\n" 2151 +"vx/1sfZD2WAcyMJ7IDmJyft7xnpVSXsyWGTT4f3eaHJIh1dqjwrso7ucAW0FK6rp\n" 2152 +"/TONyOoXNfXtRbVtxNyCWBxt4HCSclDZFvS9y8fz9ZwmCUV7jei/YdzyQI2wnE13\n" 2153 +"W8cKlpzRFL6BWi8XPrUtAw5MWeHBAPUgPWMfcmiaeyi5BJFhQCrHLi+Gj4EEJvp7\n" 2154 +"mP5cbnQAx6+paV5z9m71SKrI/WSc4ixsYYdVmlL/qwAK9YliFfoPl030YJWW6rFf\n" 2155 +"T7J9BUlHGUJ0RB2lURNNLakM+UZRkeE9TByzCzgTxuQtyv5Lwsh2mAk3ia5x0kUO\n" 2156 +"LHg3Eoabhdh+YZA5hHaxnpF7VjspB78E0F9Btq+A41rSJ6zDOdToHey4MJ2nxdey\n" 2157 +"Z3bi81TZ6Fp4IuROrvZ2B/Xl3uNKR7n+AHRKnaAO87ywzyltvjwSh2y3xhJueiRs\n" 2158 +"BiYkyL3/fnocD3pexTdN6h3JgQGgO5GV8zw/NrxA85mw8o9im0HreuFObmNj36T9\n" 2159 +"k5N+R/QIXW83cIQOLaWK1ThYcluytf0tDRiMoKqULiaA6HvDMigExLxuhCtnoF8I\n" 2160 +"iOLN1cPdEVQjzwDHLqXP2DbWW1z9iRepLZlEm1hLRLEmOrTGKezYupVv306SSa6J\n" 2161 +"OA55lAeXMbyjFaYCr54HWrpt4NwNBX1efMUURc+1LcHpzFrBTTLbfjIyq6as49pH\n" 2162 +"-----END RSA PRIVATE KEY-----\n" 2163 2164async function TestConvertPemKeyByPromise() { 2165 let asyKeyGenerator = cryptoFramework.createAsyKeyGenerator('RSA1024'); 2166 asyKeyGenerator.convertPemKey(null, priKeyPkcs1EncodingStr, "123456") 2167 .then(keyPair => { 2168 console.info('convertPemKey success.'); 2169 }).catch((error: BusinessError) => { 2170 console.error("convertPemKey error."); 2171 }); 2172} 2173``` 2174 2175### convertPemKey<sup>18+</sup> 2176 2177convertPemKey(pubKey: string | null, priKey: string | null, password: string): Promise\<KeyPair> 2178 2179Converts data into an asymmetric key. This API uses a promise to return the result. 2180 2181> **NOTE** 2182> 1. When **convertPemKey()** is used to convert an external string into an asymmetric key object defined by the Crypto framework, the public key must comply with the ASN.1 syntax, X.509 specifications, and PEM encoding format, and the private key must comply with the ASN.1 syntax, PKCS #8 specifications, and PEM encoding format. 2183> 2. In **convertPemKey()**, 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. 2184> 3. When **convertPemKey** is used to convert an external string into an asymmetric key object defined by the Crypto framework, the system does not verify whether the specifications of the generated key object are the same as the key specifications specified for the asymmetric key generator. 2185> 4. If **password** is passed in, it can be used to decrypt the encrypted private key. 2186 2187**Atomic service API**: This API can be used in atomic services since API version 18. 2188 2189**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 2190 2191**Parameters** 2192 2193| Name | Type | Mandatory| Description | 2194| ------ | -------- | ---- | ---------------- | 2195| pubKey | string \| null | Yes | Public key material to convert. If no public key is required, set this parameter to **null**.| 2196| priKey | string \| null | Yes | Private key material to convert. If no private key is required, set this parameter to **null**. <br>**NOTE**: **pubKey** and **priKey** cannot be **null** at the same time.| 2197| password | string | Yes| Password used to decrypt the private key.| 2198 2199**Return value** 2200 2201| Type | Description | 2202| ----------------- | --------------------------------- | 2203| Promise\<[KeyPair](#keypair)> | Promise used to return the key pair generated.| 2204 2205**Error codes** 2206For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 2207 2208| ID| Error Message | 2209| -------- | ---------------------- | 2210| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed. | 2211| 17620001 | memory error. | 2212| 17630001 | crypto operation error. | 2213 2214**Example** 2215 2216```ts 2217import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 2218import { BusinessError } from '@kit.BasicServicesKit'; 2219 2220let priKeyPkcs1EncodingStr : string = 2221 "-----BEGIN RSA PRIVATE KEY-----\n" 2222 +"Proc-Type: 4,ENCRYPTED\n" 2223 +"DEK-Info: AES-128-CBC,815A066131BF05CF87CE610A59CC69AE\n\n" 2224 +"7Jd0vmOmYGFZ2yRY8fqRl3+6rQlFtNcMILvcb5KWHDSrxA0ULmJE7CW0DSRikHoA\n" 2225 +"t0KgafhYXeQXh0dRy9lvVRAFSLHCLJVjchx90V7ZSivBFEq7+iTozVp4AlbgYsJP\n" 2226 +"vx/1sfZD2WAcyMJ7IDmJyft7xnpVSXsyWGTT4f3eaHJIh1dqjwrso7ucAW0FK6rp\n" 2227 +"/TONyOoXNfXtRbVtxNyCWBxt4HCSclDZFvS9y8fz9ZwmCUV7jei/YdzyQI2wnE13\n" 2228 +"W8cKlpzRFL6BWi8XPrUtAw5MWeHBAPUgPWMfcmiaeyi5BJFhQCrHLi+Gj4EEJvp7\n" 2229 +"mP5cbnQAx6+paV5z9m71SKrI/WSc4ixsYYdVmlL/qwAK9YliFfoPl030YJWW6rFf\n" 2230 +"T7J9BUlHGUJ0RB2lURNNLakM+UZRkeE9TByzCzgTxuQtyv5Lwsh2mAk3ia5x0kUO\n" 2231 +"LHg3Eoabhdh+YZA5hHaxnpF7VjspB78E0F9Btq+A41rSJ6zDOdToHey4MJ2nxdey\n" 2232 +"Z3bi81TZ6Fp4IuROrvZ2B/Xl3uNKR7n+AHRKnaAO87ywzyltvjwSh2y3xhJueiRs\n" 2233 +"BiYkyL3/fnocD3pexTdN6h3JgQGgO5GV8zw/NrxA85mw8o9im0HreuFObmNj36T9\n" 2234 +"k5N+R/QIXW83cIQOLaWK1ThYcluytf0tDRiMoKqULiaA6HvDMigExLxuhCtnoF8I\n" 2235 +"iOLN1cPdEVQjzwDHLqXP2DbWW1z9iRepLZlEm1hLRLEmOrTGKezYupVv306SSa6J\n" 2236 +"OA55lAeXMbyjFaYCr54HWrpt4NwNBX1efMUURc+1LcHpzFrBTTLbfjIyq6as49pH\n" 2237 +"-----END RSA PRIVATE KEY-----\n" 2238 2239async function TestConvertPemKeyByPromise() { 2240 let asyKeyGenerator = cryptoFramework.createAsyKeyGenerator('RSA1024'); 2241 let keyGenPromise = asyKeyGenerator.convertPemKey(null, priKeyPkcs1EncodingStr, "123456"); 2242 keyGenPromise.then(keyPair => { 2243 console.info('convertPemKey success.'); 2244 }).catch((error: BusinessError) => { 2245 console.error("convertPemKey error."); 2246 }); 2247} 2248``` 2249 2250### convertPemKeySync<sup>12+</sup> 2251 2252convertPemKeySync(pubKey: string | null, priKey: string | null): KeyPair 2253 2254Converts data into an asymmetric key pair. This API returns the result synchronously. 2255 2256> **NOTE** 2257> The precautions for using **convertPemKeySync** are the same as those for **convertPemKey**. For details, see the description of [convertPemKey](#convertpemkey12). 2258 2259**Atomic service API**: This API can be used in atomic services since API version 12. 2260 2261**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 2262 2263**Parameters** 2264 2265| Name | Type | Mandatory| Description | 2266| ------ | -------- | ---- | ---------------- | 2267| pubKey | string \| null| Yes | Public key material to convert. If no public key is required, set this parameter to **null**.| 2268| priKey | string \| null| Yes | Private key material to convert. If no private key is required, set this parameter to **null**. <br>**NOTE**: **pubKey** and **priKey** cannot be **null** at the same time.| 2269 2270**Return value** 2271 2272| Type | Description | 2273| ----------------- | --------------------------------- | 2274| [KeyPair](#keypair) | Asymmetric key pair generated.| 2275 2276**Error codes** 2277For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 2278 2279| ID| Error Message | 2280| -------- | ---------------------- | 2281| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed. | 2282| 17620001 | memory error. | 2283| 17630001 | crypto operation error. | 2284 2285**Example** 2286 2287```ts 2288import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 2289import { BusinessError } from '@kit.BasicServicesKit'; 2290 2291let priKeyPkcs1Str1024: string = 2292 "-----BEGIN RSA PRIVATE KEY-----\n" 2293 + "MIICXQIBAAKBgQCwIN3mr21+N96ToxnVnaS+xyK9cNRAHiHGgrbjHw6RAj3V+l+W\n" 2294 + "Y68IhIe3DudVlzE9oMjeOQwkMkq//HCxNlIlFR6O6pa0mrXSwPRE7YKG97CeKk2g\n" 2295 + "YOS8YEh8toAvm7xKbiLkXuuMlxrjP2j/mb5iI/UASFSPZiQ/IyxDr0AQaQIDAQAB\n" 2296 + "AoGAEvBFzBNa+7J4PXnRQlYEK/tvsd0bBZX33ceacMubHl6WVZbphltLq+fMTBPP\n" 2297 + "LjXmtpC+aJ7Lvmyl+wTi/TsxE9vxW5JnbuRT48rnZ/Xwq0eozDeEeIBRrpsr7Rvr\n" 2298 + "7ctrgzr4m4yMHq9aDgpxj8IR7oHkfwnmWr0wM3FuiVlj650CQQDineeNZ1hUTkj4\n" 2299 + "D3O+iCi3mxEVEeJrpqrmSFolRMb+iozrIRKuJlgcOs+Gqi2fHfOTTL7LkpYe8SVg\n" 2300 + "e3JxUdVLAkEAxvcZXk+byMFoetrnlcMR13VHUpoVeoV9qkv6CAWLlbMdgf7uKmgp\n" 2301 + "a1Yp3QPDNQQqkPvrqtfR19JWZ4uy1qREmwJALTU3BjyBoH/liqb6fh4HkWk75Som\n" 2302 + "MzeSjFIOubSYxhq5tgZpBZjcpvUMhV7Zrw54kwASZ+YcUJvmyvKViAm9NQJBAKF7\n" 2303 + "DyXSKrem8Ws0m1ybM7HQx5As6l3EVhePDmDQT1eyRbKp+xaD74nkJpnwYdB3jyyY\n" 2304 + "qc7A1tj5J5NmeEFolR0CQQCn76Xp8HCjGgLHw9vg7YyIL28y/XyfFyaZAzzK+Yia\n" 2305 + "akNwQ6NeGtXSsuGCcyyfpacHp9xy8qXQNKSkw03/5vDO\n" 2306 + "-----END RSA PRIVATE KEY-----\n"; 2307 let publicPkcs1Str1024: string = 2308 "-----BEGIN RSA PUBLIC KEY-----\n" 2309 + "MIGJAoGBALAg3eavbX433pOjGdWdpL7HIr1w1EAeIcaCtuMfDpECPdX6X5ZjrwiE\n" 2310 + "h7cO51WXMT2gyN45DCQySr/8cLE2UiUVHo7qlrSatdLA9ETtgob3sJ4qTaBg5Lxg\n" 2311 + "SHy2gC+bvEpuIuRe64yXGuM/aP+ZvmIj9QBIVI9mJD8jLEOvQBBpAgMBAAE=\n" 2312 + "-----END RSA PUBLIC KEY-----\n"; 2313function TestConvertPemKeyBySync() { 2314 let asyKeyGenerator = cryptoFramework.createAsyKeyGenerator('RSA1024'); 2315 try { 2316 let keyPairData = asyKeyGenerator.convertPemKeySync(publicPkcs1Str1024, priKeyPkcs1Str1024); 2317 if (keyPairData != null) { 2318 console.info('[Sync]: convert pem key pair success'); 2319 } else { 2320 console.error("[Sync]: convert pem key pair result fail!"); 2321 } 2322 } catch (e) { 2323 console.error(`Sync error, ${e.code}, ${e.message}`); 2324 } 2325} 2326``` 2327 2328### convertPemKeySync<sup>18+</sup> 2329 2330convertPemKeySync(pubKey: string | null, priKey: string | null, password: string): KeyPair 2331 2332Converts data into an asymmetric key pair. This API returns the result synchronously. 2333 2334> **NOTE** 2335> The precautions for using **convertPemKeySync** are the same as those for **convertPemKey**. For details, see the description of [convertPemKey](#convertpemkey18). 2336 2337**Atomic service API**: This API can be used in atomic services since API version 18. 2338 2339**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 2340 2341**Parameters** 2342 2343| Name | Type | Mandatory| Description | 2344| ------ | -------- | ---- | ---------------- | 2345| pubKey | string \| null| Yes | Public key material to convert. If no public key is required, set this parameter to **null**.| 2346| priKey | string \| null| Yes | Private key material to convert. If no private key is required, set this parameter to **null**. <br>**NOTE**: **pubKey** and **priKey** cannot be **null** at the same time.| 2347| password | string | Yes| Password used to decrypt the private key.| 2348 2349**Return value** 2350 2351| Type | Description | 2352| ----------------- | --------------------------------- | 2353| [KeyPair](#keypair) | Asymmetric key pair generated.| 2354 2355**Error codes** 2356For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 2357 2358| ID| Error Message | 2359| -------- | ---------------------- | 2360| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed. | 2361| 17620001 | memory error. | 2362| 17630001 | crypto operation error. | 2363 2364**Example** 2365 2366```ts 2367import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 2368import { BusinessError } from '@kit.BasicServicesKit'; 2369 2370let priKeyPkcs1EncodingStr : string = 2371 "-----BEGIN RSA PRIVATE KEY-----\n" 2372 +"Proc-Type: 4,ENCRYPTED\n" 2373 +"DEK-Info: AES-128-CBC,815A066131BF05CF87CE610A59CC69AE\n\n" 2374 +"7Jd0vmOmYGFZ2yRY8fqRl3+6rQlFtNcMILvcb5KWHDSrxA0ULmJE7CW0DSRikHoA\n" 2375 +"t0KgafhYXeQXh0dRy9lvVRAFSLHCLJVjchx90V7ZSivBFEq7+iTozVp4AlbgYsJP\n" 2376 +"vx/1sfZD2WAcyMJ7IDmJyft7xnpVSXsyWGTT4f3eaHJIh1dqjwrso7ucAW0FK6rp\n" 2377 +"/TONyOoXNfXtRbVtxNyCWBxt4HCSclDZFvS9y8fz9ZwmCUV7jei/YdzyQI2wnE13\n" 2378 +"W8cKlpzRFL6BWi8XPrUtAw5MWeHBAPUgPWMfcmiaeyi5BJFhQCrHLi+Gj4EEJvp7\n" 2379 +"mP5cbnQAx6+paV5z9m71SKrI/WSc4ixsYYdVmlL/qwAK9YliFfoPl030YJWW6rFf\n" 2380 +"T7J9BUlHGUJ0RB2lURNNLakM+UZRkeE9TByzCzgTxuQtyv5Lwsh2mAk3ia5x0kUO\n" 2381 +"LHg3Eoabhdh+YZA5hHaxnpF7VjspB78E0F9Btq+A41rSJ6zDOdToHey4MJ2nxdey\n" 2382 +"Z3bi81TZ6Fp4IuROrvZ2B/Xl3uNKR7n+AHRKnaAO87ywzyltvjwSh2y3xhJueiRs\n" 2383 +"BiYkyL3/fnocD3pexTdN6h3JgQGgO5GV8zw/NrxA85mw8o9im0HreuFObmNj36T9\n" 2384 +"k5N+R/QIXW83cIQOLaWK1ThYcluytf0tDRiMoKqULiaA6HvDMigExLxuhCtnoF8I\n" 2385 +"iOLN1cPdEVQjzwDHLqXP2DbWW1z9iRepLZlEm1hLRLEmOrTGKezYupVv306SSa6J\n" 2386 +"OA55lAeXMbyjFaYCr54HWrpt4NwNBX1efMUURc+1LcHpzFrBTTLbfjIyq6as49pH\n" 2387 +"-----END RSA PRIVATE KEY-----\n" 2388function TestConvertPemKeyBySync() { 2389 let asyKeyGenerator = cryptoFramework.createAsyKeyGenerator('RSA1024'); 2390 try { 2391 let keyPairData = asyKeyGenerator.convertPemKeySync(null, priKeyPkcs1EncodingStr, "123456"); 2392 if (keyPairData != null) { 2393 console.info('[Sync]: convert pem key pair success'); 2394 } else { 2395 console.error("[Sync]: convert pem key pair result fail!"); 2396 } 2397 } catch (e) { 2398 console.error(`Sync error, ${e.code}, ${e.message}`); 2399 } 2400} 2401``` 2402 2403## cryptoFramework.createAsyKeyGeneratorBySpec<sup>10+</sup> 2404 2405createAsyKeyGeneratorBySpec(asyKeySpec: AsyKeySpec): AsyKeyGeneratorBySpec 2406 2407Creates an **AsyKeyGenerator** instance based on the specified key parameter. 2408 2409For details about the supported specifications, see [Asymmetric Key Generation and Conversion Specifications](../../security/CryptoArchitectureKit/crypto-asym-key-generation-conversion-spec.md). 2410 2411**Atomic service API**: This API can be used in atomic services since API version 12. 2412 2413**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 2414 2415The supported system capability is SystemCapability.Security.CryptoFramework in API versions 10 to 11 and SystemCapability.Security.CryptoFramework.Key.AsymKey since API version 12. 2416 2417**Parameters** 2418 2419| Name | Type | Mandatory| Description | 2420| ------- | ------ | ---- | -------------------------------- | 2421| asyKeySpec | [AsyKeySpec](#asykeyspec10) | Yes | Key parameters. The **AsyKeyGenerator** generates the public/private key based on the specified parameters.| 2422 2423**Return value** 2424 2425| Type | Description | 2426| ----------------------------------------------- | -------------------------- | 2427| [AsyKeyGeneratorBySpec](#asykeygeneratorbyspec10) | Returns the **AsyKeyGenerator** instance created.| 2428 2429**Error codes** 2430For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 2431 2432| ID| Error Message | 2433| -------- | ---------------------- | 2434| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 2435| 801 | this operation is not supported. | 2436| 17620001 | memory error. | 2437 2438**Example** 2439 2440```ts 2441import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 2442 2443// Set the common parameters of the DSA1024 public and private keys. 2444function genDsa1024CommonSpecBigE() { 2445 let dsaCommonSpec: cryptoFramework.DSACommonParamsSpec = { 2446 algName: "DSA", 2447 specType: cryptoFramework.AsyKeySpecType.COMMON_PARAMS_SPEC, 2448 p: BigInt("0xed1501551b8ab3547f6355ffdc2913856ddeca198833dbd04f020e5f25e47c50e0b3894f7690a0d2ea5ed3a7be25c54292a698e1f086eb3a97deb4dbf04fcad2dafd94a9f35c3ae338ab35477e16981ded6a5b13d5ff20bf55f1b262303ad3a80af71aa6aa2354d20e9c82647664bdb6b333b7bea0a5f49d55ca40bc312a1729"), 2449 q: BigInt("0xd23304044019d5d382cfeabf351636c7ab219694ac845051f60b047b"), 2450 g: BigInt("0x2cc266d8bd33c3009bd67f285a257ba74f0c3a7e12b722864632a0ac3f2c17c91c2f3f67eb2d57071ef47aaa8f8e17a21ad2c1072ee1ce281362aad01dcbcd3876455cd17e1dd55d4ed36fa011db40f0bbb8cba01d066f392b5eaa9404bfcb775f2196a6bc20eeec3db32d54e94d87ecdb7a0310a5a017c5cdb8ac78597778bd"), 2451 } 2452 return dsaCommonSpec; 2453} 2454 2455// Set full parameters of the DSA1024 key pair. 2456function genDsa1024KeyPairSpecBigE() { 2457 let dsaCommonSpec = genDsa1024CommonSpecBigE(); 2458 let dsaKeyPairSpec: cryptoFramework.DSAKeyPairSpec = { 2459 algName: "DSA", 2460 specType: cryptoFramework.AsyKeySpecType.KEY_PAIR_SPEC, 2461 params: dsaCommonSpec, 2462 sk: BigInt("0xa2dd2adb2d11392c2541930f61f1165c370aabd2d78d00342e0a2fd9"), 2463 pk: BigInt("0xae6b5d5042e758f3fc9a02d009d896df115811a75b5f7b382d8526270dbb3c029403fafb8573ba4ef0314ea86f09d01e82a14d1ebb67b0c331f41049bd6b1842658b0592e706a5e4d20c14b67977e17df7bdd464cce14b5f13bae6607760fcdf394e0b73ac70aaf141fa4dafd736bd0364b1d6e6c0d7683a5de6b9221e7f2d6b"), 2464 } 2465 return dsaKeyPairSpec; 2466} 2467 2468let asyKeyPairSpec = genDsa1024KeyPairSpecBigE(); // The JS input must be a positive number in big-endian format. 2469let asyKeyGeneratorBySpec = cryptoFramework.createAsyKeyGeneratorBySpec(asyKeyPairSpec); 2470``` 2471 2472## AsyKeyGeneratorBySpec<sup>10+</sup> 2473 2474Provides APIs for using the **AsKeyGenerator**. Before using the APIs of this class, you need to use [createAsyKeyGeneratorBySpec()](#cryptoframeworkcreateasykeygeneratorbyspec10) to create an **AsyKeyGeneratorBySpec** instance. 2475 2476### Attributes 2477 2478**Atomic service API**: This API can be used in atomic services since API version 12. 2479 2480**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 2481 2482The supported system capability is SystemCapability.Security.CryptoFramework in API versions 10 to 11 and SystemCapability.Security.CryptoFramework.Key.AsymKey since API version 12. 2483 2484| Name | Type | Readable| Writable| Description | 2485| ------- | ------ | ---- | ---- | -------------------------- | 2486| algName | string | Yes | No | Algorithm used by the asymmetric key generator.| 2487 2488### generateKeyPair 2489 2490generateKeyPair(callback: AsyncCallback\<KeyPair>): void 2491 2492Generates an asymmetric key pair. This API uses an asynchronous callback to return the result. 2493 2494If a key parameter of the [COMMON_PARAMS_SPEC](#asykeyspectype10) type is used to create the key generator, a key pair will be randomly generated. If a key parameter of the [KEY_PAIR_SPEC](#asykeyspectype10) type is used to create the key generator, you can obtain a key pair that is consistent with the specified key parameters. 2495 2496**Atomic service API**: This API can be used in atomic services since API version 12. 2497 2498**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 2499 2500The supported system capability is SystemCapability.Security.CryptoFramework in API versions 9 to 11 and SystemCapability.Security.CryptoFramework.Key.AsymKey since API version 12. 2501 2502**Parameters** 2503 2504| Name | Type | Mandatory| Description | 2505| -------- | ----------------------- | ---- | ------------------------------ | 2506| callback | AsyncCallback\<[KeyPair](#keypair)> | Yes | Callback invoked to return the key pair obtained.| 2507 2508**Error codes** 2509For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 2510 2511| ID| Error Message | 2512| -------- | ----------------------- | 2513| 401 | invalid parameters. Possible causes: <br>Incorrect parameter types; | 2514| 17620001 | memory error. | 2515| 17630001 | crypto operation error. | 2516 2517**Example** 2518 2519<!--code_no_check--> 2520```ts 2521let asyKeyPairSpec: cryptoFramework.DSAKeyPairSpec; // Use DSA as an example. asyKeyPairSpec specifies full parameters of the private and public keys. The generation process is omitted here. 2522let asyKeyGeneratorBySpec = cryptoFramework.createAsyKeyGeneratorBySpec(asyKeyPairSpec); 2523asyKeyGeneratorBySpec.generateKeyPair((err, keyPair) => { 2524 if (err) { 2525 console.error("generateKeyPair: error."); 2526 return; 2527 } 2528 console.info('generateKeyPair: success.'); 2529}) 2530``` 2531 2532### generateKeyPair 2533 2534generateKeyPair(): Promise\<KeyPair> 2535 2536Generates an asymmetric key pair. This API uses a promise to return the result. 2537 2538If a key parameter of the [COMMON_PARAMS_SPEC](#asykeyspectype10) type is used to create the key generator, a key pair will be randomly generated. If a key parameter of the [KEY_PAIR_SPEC](#asykeyspectype10) type is used to create the key generator, you can obtain a key pair that is consistent with the specified key parameters. 2539 2540**Atomic service API**: This API can be used in atomic services since API version 12. 2541 2542**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 2543 2544The supported system capability is SystemCapability.Security.CryptoFramework in API versions 9 to 11 and SystemCapability.Security.CryptoFramework.Key.AsymKey since API version 12. 2545 2546**Return value** 2547 2548| Type | Description | 2549| ----------------- | --------------------------------- | 2550| Promise\<[KeyPair](#keypair)> | Promise used to return the key pair generated.| 2551 2552**Error codes** 2553For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 2554 2555| ID| Error Message | 2556| -------- | ---------------------- | 2557| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed. | 2558| 17620001 | memory error. | 2559| 17630001 | crypto operation error. | 2560 2561**Example** 2562 2563<!--code_no_check--> 2564```ts 2565import { BusinessError } from '@kit.BasicServicesKit'; 2566 2567let asyKeyPairSpec: cryptoFramework.DSAKeyPairSpec; // Use DSA as an example. asyKeyPairSpec specifies full parameters of the private and public keys. The generation process is omitted here. 2568let asyKeyGeneratorBySpec = cryptoFramework.createAsyKeyGeneratorBySpec(asyKeyPairSpec); 2569let keyGenPromise = asyKeyGeneratorBySpec.generateKeyPair(); 2570keyGenPromise.then(keyPair => { 2571 console.info('generateKeyPair success.'); 2572}).catch((error: BusinessError) => { 2573 console.error("generateKeyPair error."); 2574}); 2575``` 2576 2577### generateKeyPairSync<sup>12+</sup> 2578 2579generateKeyPairSync(): KeyPair 2580 2581Generates an asymmetric key pair. This API returns the result synchronously. 2582 2583If a key parameter of the [COMMON_PARAMS_SPEC](#asykeyspectype10) type is used to create the key generator, a key pair will be randomly generated. If a key parameter of the [KEY_PAIR_SPEC](#asykeyspectype10) type is used to create the key generator, you can obtain a key pair that is consistent with the specified key parameters. 2584 2585**Atomic service API**: This API can be used in atomic services since API version 12. 2586 2587**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 2588 2589**Return value** 2590 2591| Type | Description | 2592| ----------------- | --------------------------------- | 2593| [KeyPair](#keypair) | Asymmetric key pair generated.| 2594 2595**Error codes** 2596For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 2597 2598| ID| Error Message | 2599| -------- | ---------------------- | 2600| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed. | 2601| 17620001 | memory error. | 2602| 17630001 | crypto operation error. | 2603 2604**Example** 2605 2606<!--code_no_check--> 2607```ts 2608import { BusinessError } from '@kit.BasicServicesKit'; 2609 2610let asyKeyPairSpec: cryptoFramework.DSAKeyPairSpec; // Use DSA as an example. asyKeyPairSpec specifies full parameters of the private and public keys. The generation process is omitted here. 2611let asyKeyGeneratorBySpec = cryptoFramework.createAsyKeyGeneratorBySpec(asyKeyPairSpec); 2612try { 2613 let keyPairData = asyKeyGeneratorBySpec.generateKeyPairSync(); 2614 if (keyPairData != null) { 2615 console.info('[Sync]: key pair success'); 2616 } else { 2617 console.error("[Sync]: get key pair result fail!"); 2618 } 2619} catch (error) { 2620 let e: BusinessError = error as BusinessError; 2621 console.error(`sync error, ${e.code}, ${e.message}`); 2622} 2623``` 2624 2625### generatePriKey 2626 2627generatePriKey(callback: AsyncCallback\<PriKey>): void 2628 2629Generates an asymmetric key pair. This API uses an asynchronous callback to return the result. 2630 2631If a key parameter of the [PRIVATE_KEY_SPEC](#asykeyspectype10) type is used to create the key generator, a private key can be obtained. If a key parameter of the [KEY_PAIR_SPEC](#asykeyspectype10) type is used to create the key generator, you can obtain the private key from the key pair generated. 2632 2633**Atomic service API**: This API can be used in atomic services since API version 12. 2634 2635**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 2636 2637The supported system capability is SystemCapability.Security.CryptoFramework in API versions 9 to 11 and SystemCapability.Security.CryptoFramework.Key.AsymKey since API version 12. 2638 2639**Parameters** 2640 2641| Name | Type | Mandatory| Description | 2642| -------- | ----------------------- | ---- | ------------------------------ | 2643| callback | AsyncCallback\<[PriKey](#prikey)> | Yes | Callback invoked to return the key pair obtained.| 2644 2645**Error codes** 2646For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 2647 2648| ID| Error Message | 2649| -------- | ---------------------- | 2650| 401 | invalid parameters. Possible causes: <br>Mandatory parameters are left unspecified; | 2651| 17620001 | memory error. | 2652| 17630001 | crypto operation error. | 2653 2654**Example** 2655 2656<!--code_no_check--> 2657```ts 2658let asyKeyPairSpec: cryptoFramework.DSAKeyPairSpec; // Use DSA as an example. asyKeyPairSpec specifies full parameters of the private and public keys. The generation process is omitted here. 2659let asyKeyGeneratorBySpec = cryptoFramework.createAsyKeyGeneratorBySpec(asyKeyPairSpec); 2660asyKeyGeneratorBySpec.generatePriKey((err, prikey) => { 2661 if (err) { 2662 console.error("generatePriKey: error."); 2663 return; 2664 } 2665 console.info('generatePriKey: success.'); 2666}) 2667``` 2668 2669### generatePriKey 2670 2671generatePriKey(): Promise\<PriKey> 2672 2673Generates an asymmetric key pair. This API uses a promise to return the result. 2674 2675If a key parameter of the [PRIVATE_KEY_SPEC](#asykeyspectype10) type is used to create the key generator, a private key can be obtained. If a key parameter of the [KEY_PAIR_SPEC](#asykeyspectype10) type is used to create the key generator, you can obtain the private key from the key pair generated. 2676 2677**Atomic service API**: This API can be used in atomic services since API version 12. 2678 2679**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 2680 2681The supported system capability is SystemCapability.Security.CryptoFramework in API versions 9 to 11 and SystemCapability.Security.CryptoFramework.Key.AsymKey since API version 12. 2682 2683**Return value** 2684 2685| Type | Description | 2686| ----------------- | --------------------------------- | 2687| Promise\<[PriKey](#prikey)> | Promise used to return the key pair generated.| 2688 2689**Error codes** 2690For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 2691 2692| ID| Error Message | 2693| -------- | ---------------------- | 2694| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed. | 2695| 17620001 | memory error. | 2696| 17630001 | crypto operation error. | 2697 2698**Example** 2699 2700<!--code_no_check--> 2701```ts 2702import { BusinessError } from '@kit.BasicServicesKit'; 2703 2704let asyKeyPairSpec: cryptoFramework.DSAKeyPairSpec; // Use DSA as an example. asyKeyPairSpec specifies full parameters of the private and public keys. The generation process is omitted here. 2705let asyKeyGeneratorBySpec = cryptoFramework.createAsyKeyGeneratorBySpec(asyKeyPairSpec); 2706let keyGenPromise = asyKeyGeneratorBySpec.generatePriKey(); 2707keyGenPromise.then(priKey => { 2708 console.info('generatePriKey success.'); 2709}).catch((error: BusinessError) => { 2710 console.error("generatePriKey error."); 2711}); 2712``` 2713 2714### generatePriKeySync<sup>12+</sup> 2715 2716generatePriKeySync(): PriKey 2717 2718Generates a private key randomly. This API returns the result synchronously. 2719 2720If a key parameter of the [PRIVATE_KEY_SPEC](#asykeyspectype10) type is used to create the key generator, a private key can be obtained. If a key parameter of the [KEY_PAIR_SPEC](#asykeyspectype10) type is used to create the key generator, you can obtain the private key from the key pair generated. 2721 2722**Atomic service API**: This API can be used in atomic services since API version 12. 2723 2724**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 2725 2726**Return value** 2727 2728| Type | Description | 2729| ----------------- | --------------------------------- | 2730| [PriKey](#prikey) | Private key generated.| 2731 2732**Error codes** 2733For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 2734 2735| ID| Error Message | 2736| -------- | ---------------------- | 2737| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed. | 2738| 17620001 | memory error. | 2739| 17630001 | crypto operation error. | 2740 2741**Example** 2742 2743<!--code_no_check--> 2744```ts 2745let asyKeyPairSpec: cryptoFramework.DSAKeyPairSpec; // Use DSA as an example. asyKeyPairSpec specifies full parameters of the private and public keys. The generation process is omitted here. 2746let asyKeyGeneratorBySpec = cryptoFramework.createAsyKeyGeneratorBySpec(asyKeyPairSpec); 2747try { 2748 let priKeyData = asyKeyGeneratorBySpec.generatePriKeySync(); 2749 if (priKeyData != null) { 2750 console.info('[Sync]: pri key success'); 2751 } else { 2752 console.error("[Sync]: get pri key result fail!"); 2753 } 2754} catch (e) { 2755 console.error(`sync error, ${e.code}, ${e.message}`); 2756} 2757``` 2758 2759### generatePubKey 2760 2761generatePubKey(callback: AsyncCallback\<PubKey>): void 2762 2763Generates an asymmetric key pair. This API uses an asynchronous callback to return the result. 2764 2765If a key parameter of the [PUBLIC_KEY_SPEC](#asykeyspectype10) type is used to create the key generator, the specified public key can be obtained. If a key parameter of the [KEY_PAIR_SPEC](#asykeyspectype10) type is used to create the key generator, you can obtain the specified public key from the key pair generated. 2766 2767**Atomic service API**: This API can be used in atomic services since API version 12. 2768 2769**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 2770 2771The supported system capability is SystemCapability.Security.CryptoFramework in API versions 9 to 11 and SystemCapability.Security.CryptoFramework.Key.AsymKey since API version 12. 2772 2773**Parameters** 2774 2775| Name | Type | Mandatory| Description | 2776| -------- | ----------------------- | ---- | ------------------------------ | 2777| callback | AsyncCallback\<[PubKey](#pubkey)> | Yes | Callback invoked to return the key pair obtained.| 2778 2779**Error codes** 2780For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 2781 2782| ID| Error Message | 2783| -------- | ---------------------- | 2784| 401 | invalid parameters. Possible causes:<br> Incorrect parameter types; | 2785| 17620001 | memory error. | 2786| 17630001 | crypto operation error. | 2787 2788**Example** 2789 2790<!--code_no_check--> 2791```ts 2792let asyKeyPairSpec: cryptoFramework.DSAKeyPairSpec; // Use DSA as an example. asyKeyPairSpec specifies full parameters of the private and public keys. The generation process is omitted here. 2793let asyKeyGeneratorBySpec = cryptoFramework.createAsyKeyGeneratorBySpec(asyKeyPairSpec); 2794asyKeyGeneratorBySpec.generatePubKey((err, pubKey) => { 2795 if (err) { 2796 console.error("generatePubKey: error."); 2797 return; 2798 } 2799 console.info('generatePubKey: success.'); 2800}) 2801``` 2802 2803### generatePubKey 2804 2805generatePubKey(): Promise\<PubKey> 2806 2807Generates an asymmetric key pair. This API uses a promise to return the result. 2808 2809If a key parameter of the [PUBLIC_KEY_SPEC](#asykeyspectype10) type is used to create the key generator, the specified public key can be obtained. If a key parameter of the [KEY_PAIR_SPEC](#asykeyspectype10) type is used to create the key generator, you can obtain the specified public key from the key pair generated. 2810 2811**Atomic service API**: This API can be used in atomic services since API version 12. 2812 2813**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 2814 2815The supported system capability is SystemCapability.Security.CryptoFramework in API versions 9 to 11 and SystemCapability.Security.CryptoFramework.Key.AsymKey since API version 12. 2816 2817**Return value** 2818 2819| Type | Description | 2820| ----------------- | --------------------------------- | 2821| Promise\<[PubKey](#pubkey)> | Promise used to return the key pair generated.| 2822 2823**Error codes** 2824For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 2825 2826| ID| Error Message | 2827| -------- | ---------------------- | 2828| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed. | 2829| 17620001 | memory error. | 2830| 17630001 | crypto operation error. | 2831 2832**Example** 2833 2834<!--code_no_check--> 2835```ts 2836import { BusinessError } from '@kit.BasicServicesKit'; 2837 2838let asyKeyPairSpec: cryptoFramework.DSAKeyPairSpec; // Use DSA as an example. asyKeyPairSpec specifies full parameters of the private and public keys. The generation process is omitted here. 2839let asyKeyGeneratorBySpec = cryptoFramework.createAsyKeyGeneratorBySpec(asyKeyPairSpec); 2840let keyGenPromise = asyKeyGeneratorBySpec.generatePubKey(); 2841keyGenPromise.then(pubKey => { 2842 console.info('generatePubKey success.'); 2843}).catch((error: BusinessError) => { 2844 console.error("generatePubKey error."); 2845}); 2846``` 2847 2848### generatePubKeySync<sup>12+</sup> 2849 2850generatePubKeySync(): PubKey 2851 2852Generates a public key. This API returns the result synchronously. 2853 2854If a key parameter of the [PUBLIC_KEY_SPEC](#asykeyspectype10) type is used to create the key generator, the specified public key can be obtained. If a key parameter of the [KEY_PAIR_SPEC](#asykeyspectype10) type is used to create the key generator, you can obtain the specified public key from the key pair generated. 2855 2856**Atomic service API**: This API can be used in atomic services since API version 12. 2857 2858**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 2859 2860**Return value** 2861 2862| Type | Description | 2863| ----------------- | --------------------------------- | 2864| [PubKey](#pubkey) | Private key generated.| 2865 2866**Error codes** 2867For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 2868 2869| ID| Error Message | 2870| -------- | ---------------------- | 2871| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed. | 2872| 17620001 | memory error. | 2873| 17630001 | crypto operation error. | 2874 2875**Example** 2876 2877<!--code_no_check--> 2878```ts 2879let asyKeyPairSpec: cryptoFramework.DSAKeyPairSpec; // Use DSA as an example. asyKeyPairSpec specifies full parameters of the private and public keys. The generation process is omitted here. 2880let asyKeyGeneratorBySpec = cryptoFramework.createAsyKeyGeneratorBySpec(asyKeyPairSpec); 2881try { 2882 let pubKeyData = asyKeyGeneratorBySpec.generatePubKeySync(); 2883 if (pubKeyData != null) { 2884 console.info('[Sync]: pub key success'); 2885 } else { 2886 console.error("[Sync]: get pub key result fail!"); 2887 } 2888} catch (e) { 2889 console.error(`sync error, ${e.code}, ${e.message}`); 2890} 2891``` 2892 2893## ECCKeyUtil<sup>11+</sup> 2894 2895Provides APIs for generating common parameters for an asymmetric key pair based on the elliptic curve name. 2896 2897### genECCCommonParamsSpec<sup>11+</sup> 2898 2899static genECCCommonParamsSpec(curveName: string): ECCCommonParamsSpec 2900 2901Generates common parameters for an asymmetric key pair based on the specified name identifier (NID) of an elliptic curve. For details, see [ECC](../../security/CryptoArchitectureKit/crypto-asym-key-generation-conversion-spec.md#ecc) and [SM2](../../security/CryptoArchitectureKit/crypto-asym-key-generation-conversion-spec.md#sm2). 2902 2903**Atomic service API**: This API can be used in atomic services since API version 12. 2904 2905**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 2906 2907The supported system capability is SystemCapability.Security.CryptoFramework in API version 11 and SystemCapability.Security.CryptoFramework.Key.AsymKey since API version 12. 2908 2909**Parameters** 2910 2911| Name | Type | Mandatory| Description | 2912| ------- | ------ | ---- | ---------------------------------------------- | 2913| curveName | string | Yes | NID of the elliptic curve.| 2914 2915**Return value** 2916 2917| Type | Description | 2918| ----------------- | --------------------------------- | 2919| [ECCCommonParamsSpec](#ecccommonparamsspec10) | ECC common parameters generated.| 2920 2921**Error codes** 2922For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 2923 2924| ID| Error Message | 2925| -------- | -------------------------------- | 2926| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 2927| 801 | this operation is not supported. | 2928| 17620001 | memory error. | 2929 2930**Example** 2931 2932```ts 2933import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 2934import { BusinessError } from '@kit.BasicServicesKit'; 2935try { 2936 let ECCCommonParamsSpec = cryptoFramework.ECCKeyUtil.genECCCommonParamsSpec('NID_brainpoolP160r1'); 2937 console.info('genECCCommonParamsSpec success'); 2938} catch (err) { 2939 let e: BusinessError = err as BusinessError; 2940 console.error(`genECCCommonParamsSpec error, ${e.code}, ${e.message}`); 2941} 2942``` 2943 2944### convertPoint<sup>12+</sup> 2945 2946static convertPoint(curveName: string, encodedPoint: Uint8Array): Point 2947 2948Converts the specified point data into a **Point** object based on the curve name, that is, Name IDentifier (NID). Currently, compressed and uncompressed point data is supported. 2949 2950> **NOTE** 2951> 2952> According to section 2.2 in RFC 5480:<br> 2953> 1. The uncompressed point data is represented as **0x04**\|x coordinate\|y coordinate. 2954> 2. The compressed point data in the **Fp** field (the **F2m** field is not supported currently) is represented as follows: **0x03**\|x coordinate (when the coordinate y is an odd number); **0x02**\|x coordinate (when the coordinate y is an even number). 2955 2956**Atomic service API**: This API can be used in atomic services since API version 12. 2957 2958**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 2959 2960**Parameters** 2961 2962| Name | Type | Mandatory| Description | 2963| ------------ | ---------- | ---- | ---------------------------------------------- | 2964| curveName | string | Yes | Elliptic curve name that is, the NID.| 2965| encodedPoint | Uint8Array | Yes | Data of the point on the ECC elliptic curve to convert.| 2966 2967**Return value** 2968 2969| Type | Description | 2970| ----------------- | ------------------- | 2971| [Point](#point10) | **Point** object obtained.| 2972 2973**Error codes** 2974For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 2975 2976| ID| Error Message | 2977| -------- | ---------------------- | 2978| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 2979| 17620001 | memory error. | 2980| 17630001 | crypto operation error. | 2981 2982**Example** 2983 2984```ts 2985import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 2986 2987// Randomly generated uncompressed point data. 2988let pkData = new Uint8Array([4, 143, 39, 57, 249, 145, 50, 63, 222, 35, 70, 178, 121, 202, 154, 21, 146, 129, 75, 76, 63, 8, 195, 157, 111, 40, 217, 215, 148, 120, 224, 205, 82, 83, 92, 185, 21, 211, 184, 5, 19, 114, 33, 86, 85, 228, 123, 242, 206, 200, 98, 178, 184, 130, 35, 232, 45, 5, 202, 189, 11, 46, 163, 156, 152]); 2989let returnPoint = cryptoFramework.ECCKeyUtil.convertPoint('NID_brainpoolP256r1', pkData); 2990console.info('returnPoint: ' + returnPoint.x.toString(16)); 2991``` 2992 2993### getEncodedPoint<sup>12+</sup> 2994 2995static getEncodedPoint(curveName: string, point: Point, format: string): Uint8Array 2996 2997Obtains the point data in the specified format from a **Point** object. Currently, compressed and uncompressed point data is supported. 2998 2999**Atomic service API**: This API can be used in atomic services since API version 12. 3000 3001**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 3002 3003**Parameters** 3004 3005| Name | Type | Mandatory| Description | 3006| ------------ | ----------------- | ---- | ---------------------------------------------- | 3007| curveName | string | Yes | Elliptic curve name that is, the NID.| 3008| point | [Point](#point10) | Yes | **Point** object of the elliptic curve.| 3009| format | string | Yes | Format of the point data to obtain. Currently, the value can be **COMPRESSED** or **UNCOMPRESSED** only.| 3010 3011**Return value** 3012 3013| Type | Description | 3014| ----------------- | --------------------------------- | 3015| Uint8Array | Point data in the specified format.| 3016 3017**Error codes** 3018For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 3019 3020| ID| Error Message | 3021| -------- | ---------------------- | 3022| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 3023| 17620001 | memory error. | 3024| 17630001 | crypto operation error. | 3025 3026**Example** 3027 3028```ts 3029import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 3030 3031async function doTest() { 3032 let generator = cryptoFramework.createAsyKeyGenerator('ECC_BrainPoolP256r1'); 3033 let keyPair = await generator.generateKeyPair(); 3034 let eccPkX = keyPair.pubKey.getAsyKeySpec(cryptoFramework.AsyKeySpecItem.ECC_PK_X_BN); 3035 let eccPkY = keyPair.pubKey.getAsyKeySpec(cryptoFramework.AsyKeySpecItem.ECC_PK_Y_BN); 3036 console.info('ECC_PK_X_BN 16: ' + eccPkX.toString(16)); 3037 console.info('ECC_PK_Y_BN 16: ' + eccPkY.toString(16)); 3038 // Place eccPkX.toString(16) in x and eccPkY.toString(16) in y. 3039 let returnPoint: cryptoFramework.Point = { 3040 x: BigInt('0x' + eccPkX.toString(16)), 3041 y: BigInt('0x' + eccPkY.toString(16)) 3042 }; 3043 let returnData = cryptoFramework.ECCKeyUtil.getEncodedPoint('NID_brainpoolP256r1', returnPoint, 'UNCOMPRESSED'); 3044 console.info('returnData: ' + returnData); 3045} 3046``` 3047 3048## DHKeyUtil<sup>11+</sup> 3049 3050Provides APIs for generating common parameters for a DH key based on the prime **p** length and the private key length. 3051 3052### genDHCommonParamsSpec<sup>11+</sup> 3053 3054static genDHCommonParamsSpec(pLen: number, skLen?: number): DHCommonParamsSpec 3055 3056Generates common parameters for a DH key based on the prime **p** length and the private key length. For details, see [DH](../../security/CryptoArchitectureKit/crypto-asym-key-generation-conversion-spec.md#dh). 3057 3058**Atomic service API**: This API can be used in atomic services since API version 12. 3059 3060**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 3061 3062The supported system capability is SystemCapability.Security.CryptoFramework in API version 11 and SystemCapability.Security.CryptoFramework.Key.AsymKey since API version 12. 3063 3064**Parameters** 3065 3066| Name| Type | Mandatory| Description | 3067| ------ | ------ | ---- | ------------------------------------------------ | 3068| pLen | number | Yes | Length of the prime **p**, in bits.| 3069| skLen | number | No | Length of the private key, in bits. | 3070 3071**Return value** 3072 3073| Type | Description | 3074| ----------------- | --------------------------------- | 3075| [DHCommonParamsSpec](#dhcommonparamsspec11) | DH common parameters generated.| 3076 3077**Error codes** 3078For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 3079 3080| ID| Error Message | 3081| -------- | -------------------------------- | 3082| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 3083| 801 | this operation is not supported. | 3084| 17620001 | memory error. | 3085| 17630001 | crypto operation error. | 3086 3087**Example** 3088 3089```ts 3090import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 3091import { BusinessError } from '@kit.BasicServicesKit'; 3092try { 3093 let DHCommonParamsSpec = cryptoFramework.DHKeyUtil.genDHCommonParamsSpec(2048); 3094 console.info('genDHCommonParamsSpec success'); 3095} catch (err) { 3096 let e: BusinessError = err as BusinessError; 3097 console.error(`genDHCommonParamsSpec error, ${e.code}, ${e.message}`); 3098} 3099``` 3100 3101## SM2CryptoUtil<sup>12+</sup> 3102 3103Provides APIs for SM2 cryptographic operations. 3104 3105### genCipherTextBySpec<sup>12+</sup> 3106 3107static genCipherTextBySpec(spec: SM2CipherTextSpec, mode?: string): DataBlob 3108 3109Generates SM2 ciphertext in ASN.1 format. 3110 3111**Atomic service API**: This API can be used in atomic services since API version 12. 3112 3113**System capability**: SystemCapability.Security.CryptoFramework.Cipher 3114 3115**Parameters** 3116 3117| Name| Type | Mandatory| Description | 3118| ------ | ------ | ---- | ------------------------------------------------ | 3119| spec | [SM2CipherTextSpec](#sm2ciphertextspec12) | Yes | SM2 ciphertext parameters.| 3120| mode | string | No | Order of the SM2 parameters in the ciphertext. Currently, only C1C3C2 is supported. | 3121 3122**Return value** 3123 3124| Type | Description | 3125| ----------------- | --------------------------------- | 3126| [DataBlob](#datablob) | SM2 ciphertext in ASN.1 format.| 3127 3128**Error codes** 3129For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 3130 3131| ID| Error Message | 3132| -------- | -------------------------------- | 3133| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 3134| 17620001 | memory error. | 3135| 17630001 | crypto operation error. | 3136 3137**Example** 3138 3139```ts 3140import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 3141import { BusinessError } from '@kit.BasicServicesKit'; 3142try { 3143 let spec : cryptoFramework.SM2CipherTextSpec = { 3144 xCoordinate: BigInt('20625015362595980457695435345498579729138244358573902431560627260141789922999'), 3145 yCoordinate: BigInt('48563164792857017065725892921053777369510340820930241057309844352421738767712'), 3146 cipherTextData: new Uint8Array([100,227,78,195,249,179,43,70,242,69,169,10,65,123]), 3147 hashData: new Uint8Array([87,167,167,247,88,146,203,234,83,126,117,129,52,142,82,54,152,226,201,111,143,115,169,125,128,42,157,31,114,198,109,244]), 3148 } 3149 let data = cryptoFramework.SM2CryptoUtil.genCipherTextBySpec(spec, 'C1C3C2'); 3150 console.info('genCipherTextBySpec success'); 3151} catch (err) { 3152 let e: BusinessError = err as BusinessError; 3153 console.error(`genCipherTextBySpec error, ${e.code}, ${e.message}`); 3154} 3155``` 3156 3157### getCipherTextSpec<sup>12+</sup> 3158 3159static getCipherTextSpec(cipherText: DataBlob, mode?: string): SM2CipherTextSpec 3160 3161Obtains SM2 ciphertext parameters from the SM2 ciphertext in ASN.1 format. 3162 3163**Atomic service API**: This API can be used in atomic services since API version 12. 3164 3165**System capability**: SystemCapability.Security.CryptoFramework.Cipher 3166 3167**Parameters** 3168 3169| Name| Type | Mandatory| Description | 3170| ------ | ------ | ---- | ------------------------------------------------ | 3171| cipherText | [DataBlob](#datablob) | Yes | SM2 ciphertext in ASN.1 format. 3172| mode | string | No | Order of the SM2 parameters in the ciphertext. Currently, only C1C3C2 is supported. | 3173 3174**Return value** 3175 3176| Type | Description | 3177| ----------------- | --------------------------------- | 3178| [SM2CipherTextSpec](#sm2ciphertextspec12) | SM2 ciphertext parameters obtained.| 3179 3180**Error codes** 3181For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 3182 3183| ID| Error Message | 3184| -------- | -------------------------------- | 3185| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 3186| 17620001 | memory error. | 3187| 17630001 | crypto operation error. | 3188 3189```ts 3190import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 3191import { BusinessError } from '@kit.BasicServicesKit'; 3192try { 3193 let cipherTextArray = new Uint8Array([48,118,2,32,45,153,88,82,104,221,226,43,174,21,122,248,5,232,105,41,92,95,102,224,216,149,85,236,110,6,64,188,149,70,70,183,2,32,107,93,198,247,119,18,40,110,90,156,193,158,205,113,170,128,146,109,75,17,181,109,110,91,149,5,110,233,209,78,229,96,4,32,87,167,167,247,88,146,203,234,83,126,117,129,52,142,82,54,152,226,201,111,143,115,169,125,128,42,157,31,114,198,109,244,4,14,100,227,78,195,249,179,43,70,242,69,169,10,65,123]); 3194 let cipherText : cryptoFramework.DataBlob = {data : cipherTextArray}; 3195 let spec : cryptoFramework.SM2CipherTextSpec = cryptoFramework.SM2CryptoUtil.getCipherTextSpec(cipherText, 'C1C3C2'); 3196 console.info('getCipherTextSpec success'); 3197} catch (err) { 3198 let e: BusinessError = err as BusinessError; 3199 console.error(`getCipherTextSpec error, ${e.code}, ${e.message}`); 3200} 3201``` 3202 3203## cryptoFramework.createCipher 3204 3205createCipher(transformation: string): Cipher 3206 3207Creates a [Cipher](#cipher) instance based on the specified algorithm. 3208 3209For details about the supported specifications, see [Symmetric Key Encryption and Decryption Algorithm Specifications](../../security/CryptoArchitectureKit/crypto-sym-encrypt-decrypt-spec.md) and [Asymmetric Key Encryption and Decryption Algorithm Specifications](../../security/CryptoArchitectureKit/crypto-asym-encrypt-decrypt-spec.md). 3210 3211**Atomic service API**: This API can be used in atomic services since API version 12. 3212 3213**System capability**: SystemCapability.Security.CryptoFramework.Cipher 3214 3215The supported system capability is SystemCapability.Security.CryptoFramework in API versions 9 to 11 and SystemCapability.Security.CryptoFramework.Cipher since API version 12. 3216 3217**Parameters** 3218 3219| Name | Type | Mandatory| Description | 3220| -------------- | ------ | ---- | ------------------------------------------------------------ | 3221| transformation | string | Yes | Combination of the algorithm name (including the key length), encryption mode, and padding algorithm of the **Cipher** instance to create.| 3222 3223> **NOTE** 3224> 3225> 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. 3226> 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. 3227> 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. 3228 3229**Return value** 3230 3231| Type | Description | 3232| ----------------- | ------------------------ | 3233| [Cipher](#cipher) | [Cipher](#cipher) instance created.| 3234 3235**Error codes** 3236For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 3237 3238| ID| Error Message | 3239| -------- | ---------------------- | 3240| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 3241| 801 | this operation is not supported. | 3242| 17620001 | memory error. | 3243 3244**Example** 3245 3246```ts 3247import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 3248import { BusinessError } from '@kit.BasicServicesKit'; 3249 3250let cipherAlgName = '3DES192|ECB|PKCS7'; 3251try { 3252 let cipher = cryptoFramework.createCipher(cipherAlgName); 3253 console.info('cipher algName: ' + cipher.algName); 3254} catch (error) { 3255 let e: BusinessError = error as BusinessError; 3256 console.error(`sync error, ${e.code}, ${e.message}`); 3257} 3258``` 3259 3260## Cipher 3261 3262Provides APIs for cipher operations. The [init()](#init-1), [update()](#update), and [doFinal()](#dofinal) APIs in this class are called in sequence to implement symmetric encryption or decryption and asymmetric encryption or decryption. 3263 3264For details about the encryption and decryption process, see [Encryption and Decryption Overview](../../security/CryptoArchitectureKit/crypto-encryption-decryption-overview.md). 3265 3266A complete symmetric encryption/decryption process is slightly different from the asymmetric encryption/decryption process. 3267 3268- 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. 3269- 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. 3270 3271### Attributes 3272 3273**Atomic service API**: This API can be used in atomic services since API version 12. 3274 3275**System capability**: SystemCapability.Security.CryptoFramework.Cipher 3276 3277The supported system capability is SystemCapability.Security.CryptoFramework in API versions 9 to 11 and SystemCapability.Security.CryptoFramework.Cipher since API version 12. 3278 3279| Name | Type | Readable| Writable| Description | 3280| ------- | ------ | ---- | ---- | ---------------------------- | 3281| algName | string | Yes | No | Algorithm.| 3282 3283### init 3284 3285init(opMode: CryptoMode, key: Key, params: ParamsSpec | null, callback: AsyncCallback\<void>): void 3286 3287Initializes a [cipher](#cipher) instance. This API uses an asynchronous callback to return the result. **init**, **update**, and **doFinal** must be used together. **init** and **doFinal** are mandatory, and **update** is optional. 3288 3289This API can be used only after a [Cipher](#cipher) instance is created by using [createCipher](#cryptoframeworkcreatecipher). 3290 3291**Atomic service API**: This API can be used in atomic services since API version 12. 3292 3293**System capability**: SystemCapability.Security.CryptoFramework.Cipher 3294 3295The supported system capability is SystemCapability.Security.CryptoFramework in API versions 9 to 11 and SystemCapability.Security.CryptoFramework.Cipher since API version 12. 3296 3297**Parameters** 3298 3299| Name | Type | Mandatory| Description | 3300| -------- | ------------------------- | ---- | ------------------------------------------------------------ | 3301| opMode | [CryptoMode](#cryptomode) | Yes | Operation (encryption or decryption) to perform. | 3302| key | [Key](#key) | Yes | Key for encryption or decryption. | 3303| 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.| 3304| callback | AsyncCallback\<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object. | 3305 3306**Error codes** 3307For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 3308 3309| ID| Error Message | 3310| -------- | --------------------------------------------------------- | 3311| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 3312| 17620001 | memory error. | 3313| 17620002 | runtime error. | 3314| 17630001 | crypto operation error.| 3315 3316### init 3317 3318init(opMode: CryptoMode, key: Key, params: ParamsSpec | null): Promise\<void> 3319 3320Initializes a [cipher](#cipher) instance. This API uses a promise to return the result. **init**, **update**, and **doFinal** must be used together. **init** and **doFinal** are mandatory, and **update** is optional. 3321 3322This API can be used only after a [Cipher](#cipher) instance is created by using [createCipher](#cryptoframeworkcreatecipher). 3323 3324**Atomic service API**: This API can be used in atomic services since API version 12. 3325 3326**System capability**: SystemCapability.Security.CryptoFramework.Cipher 3327 3328The supported system capability is SystemCapability.Security.CryptoFramework in API versions 9 to 11 and SystemCapability.Security.CryptoFramework.Cipher since API version 12. 3329 3330**Parameters** 3331 3332| Name | Type | Mandatory| Description | 3333| ------ | ------------------------- | ---- | ------------------------------------------------------------ | 3334| opMode | [CryptoMode](#cryptomode) | Yes | Operation (encryption or decryption) to perform. | 3335| key | [Key](#key) | Yes | Key for encryption or decryption. | 3336| 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.| 3337 3338**Return value** 3339 3340| Type | Description | 3341| -------------- | -------------------------------------- | 3342| Promise\<void> | Promise that returns no value.| 3343 3344**Error codes** 3345For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 3346 3347| ID| Error Message | 3348| -------- | ------------------------------------------------- | 3349| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 3350| 17620001 | memory error. | 3351| 17620002 | runtime error. | 3352| 17630001 | crypto operation error.| 3353 3354### initSync<sup>12+</sup> 3355 3356initSync(opMode: CryptoMode, key: Key, params: ParamsSpec | null): void 3357 3358Initializes a [cipher](#cipher) instance. This API returns the result synchronously. **initSync**, **updateSync**, and **doFinalSync** must be used together. **initSync** and **doFinalSync** are mandatory, and **updateSync** is optional. 3359 3360This API can be used only after a [Cipher](#cipher) instance is created by using [createCipher](#cryptoframeworkcreatecipher). 3361 3362**Atomic service API**: This API can be used in atomic services since API version 12. 3363 3364**System capability**: SystemCapability.Security.CryptoFramework.Cipher 3365 3366**Parameters** 3367 3368| Name| Type | Mandatory| Description | 3369| ------ | ----------------------------------------------- | ---- | ------------------------------------------------------------ | 3370| opMode | [CryptoMode](#cryptomode) | Yes | Operation (encryption or decryption) to perform. | 3371| key | [Key](#key) | Yes | Key for encryption or decryption. | 3372| params | [ParamsSpec](#paramsspec) | Yes | Parameters for encryption or decryption. For algorithm modes without parameters (such as ECB), **null** can be passed in.| 3373 3374**Error codes** 3375For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 3376 3377| ID| Error Message | 3378| -------- | ----------------------- | 3379| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 3380| 17620001 | memory error. | 3381| 17620002 | runtime error. | 3382| 17630001 | crypto operation error. | 3383 3384### update 3385 3386update(data: DataBlob, callback: AsyncCallback\<DataBlob>): void 3387 3388Updates the data to encrypt or decrypt by segment. This API uses an asynchronous callback to return the encrypted or decrypted data. 3389 3390This API can be called only after the [Cipher](#cipher) instance is initialized by using [init()](#init-1). 3391 3392> **NOTE** 3393> 3394> 1. The **update()** and **doFinal()** operation results vary with the block mode used. If you are not familiar with the block modes for symmetric encryption and decryption, add a judgment to determine whether the result of each **update()** and **doFinal()** is null. If the result is not null, obtain and combine the data segments into complete ciphertext or plaintext. <br>For example, in ECB or CBC mode, 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 data generated by this **update()** is output.<br>That is, 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. 3395> 2. You can use **update()** multiple times or do not use it (use **doFinal()** after **init()**), depending on the data volume.<br> 3396> The amount of the data to be passed in by **update** (one-time or accumulative) is not limited. If there is a large amount of data, you are advised to call **update()** multiple times to pass in the data by segment.<br> 3397> For details about the sample code for calling **update** multiple times, see [Encryption and Decryption by Segment with an AES Symmetric Key (GCM Mode)](../../security/CryptoArchitectureKit/crypto-aes-sym-encrypt-decrypt-gcm-by-segment.md). 3398> 3. RSA or SM2 asymmetric encryption and decryption do not support **update()**. 3399> 4. If CCM is used in symmetric encryption or decryption, **update()** can be called only once. In the encryption process, you can either use **update()** to encrypt data and use **doFinal()** to obtain **authTag** or use **doFinal()** without using **update()**. In the decryption process, you can either use **update()** once or use **doFinal()** to decrypt data and verify the tag. 3400 3401**Atomic service API**: This API can be used in atomic services since API version 12. 3402 3403**System capability**: SystemCapability.Security.CryptoFramework.Cipher 3404 3405The supported system capability is SystemCapability.Security.CryptoFramework in API versions 9 to 11 and SystemCapability.Security.CryptoFramework.Cipher since API version 12. 3406 3407**Parameters** 3408 3409| Name | Type | Mandatory| Description | 3410| -------- | ------------------------------------- | ---- | ------------------------------------------------------------ | 3411| data | [DataBlob](#datablob) | Yes | Data to encrypt or decrypt. It cannot be null. | 3412| 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.| 3413 3414**Error codes** 3415For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 3416 3417| ID| Error Message | 3418| -------- | ------------------------------------------- | 3419| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 3420| 17620001 | memory error. | 3421| 17620002 | runtime error. | 3422| 17630001 | crypto operation error. | 3423 3424### update 3425 3426update(data: DataBlob): Promise\<DataBlob> 3427 3428Updates the data to encrypt or decrypt by segment. This API uses a promise to return the encrypted or decrypted data. 3429 3430This API can be called only after the [Cipher](#cipher) instance is initialized by using [init()](#init-2). 3431 3432> **NOTE** 3433> 3434> 1. The **update()** and **doFinal()** operation results vary with the block mode used. If you are not familiar with the block modes for symmetric encryption and decryption, add a judgment to determine whether the result of each **update()** and **doFinal()** is null. If the result is not null, obtain and combine the data segments into complete ciphertext or plaintext. 3435> <br>For example, in ECB or CBC mode, 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 data generated by this **update()** is output.<br>That is, 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. 3436> 2. You can use **update()** multiple times or do not use it (use **doFinal()** after **init()**), depending on the data volume.<br> 3437> The amount of the data to be passed in by **update()** (one-time or accumulative) is not limited. If there is a large amount of data, you are advised to call **update()** multiple times to pass in the data by segment.<br> 3438> For details about the sample code for calling **update()** multiple times, see [Encryption and Decryption by Segment with an AES Symmetric Key (GCM Mode)](../../security/CryptoArchitectureKit/crypto-aes-sym-encrypt-decrypt-gcm-by-segment.md). 3439> 3. RSA or SM2 asymmetric encryption and decryption do not support **update()**. 3440> 4. If CCM is used in symmetric encryption or decryption, **update()** can be called only once. In the encryption process, you can either use **update()** to encrypt data and use **doFinal()** to obtain **authTag** or use **doFinal()** without using **update()**. In the decryption process, you can either use **update()** once or use **doFinal()** to decrypt data and verify the tag. 3441 3442**Atomic service API**: This API can be used in atomic services since API version 12. 3443 3444**System capability**: SystemCapability.Security.CryptoFramework.Cipher 3445 3446The supported system capability is SystemCapability.Security.CryptoFramework in API versions 9 to 11 and SystemCapability.Security.CryptoFramework.Cipher since API version 12. 3447 3448**Parameters** 3449 3450| Name| Type | Mandatory| Description | 3451| ---- | --------------------- | ---- | -------------------- | 3452| data | [DataBlob](#datablob) | Yes | Data to encrypt or decrypt. It cannot be null.| 3453 3454**Return value** 3455 3456| Type | Description | 3457| ------------------------------- | ------------------------------------------------ | 3458| Promise\<[DataBlob](#datablob)> | Promise used to return the **DataBlob** (containing the encrypted or decrypted data).| 3459 3460**Error codes** 3461For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 3462 3463| ID| Error Message | 3464| -------- | -------------------------------------------- | 3465| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 3466| 17620001 | memory error. | 3467| 17620002 | runtime error. | 3468| 17630001 | crypto operation error. | 3469 3470### updateSync<sup>12+</sup> 3471 3472updateSync(data: DataBlob): DataBlob 3473 3474Updates the data to encrypt or decrypt by segment. This API returns the encrypted or decrypted data synchronously. 3475 3476This API can be called only after the [Cipher](#cipher) instance is initialized by using [initSync()](#initsync12). 3477 3478See **NOTE** in **update()** for other precautions. 3479 3480**Atomic service API**: This API can be used in atomic services since API version 12. 3481 3482**System capability**: SystemCapability.Security.CryptoFramework.Cipher 3483 3484**Parameters** 3485 3486| Name| Type | Mandatory| Description | 3487| ------ | --------------------- | ---- | ------------------------------------------------------------ | 3488| data | [DataBlob](#datablob) | Yes | Data to encrypt or decrypt. It cannot be null.| 3489 3490**Error codes** 3491For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 3492 3493| ID| Error Message | 3494| -------- | ----------------------- | 3495| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 3496| 17620001 | memory error. | 3497| 17620002 | runtime error. | 3498| 17630001 | crypto operation error. | 3499 3500### doFinal 3501 3502doFinal(data: DataBlob | null, callback: AsyncCallback\<DataBlob>): void 3503 3504 (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. 3505 3506- 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**. **authTag** must be [GcmParamsSpec](#gcmparamsspec) or [CcmParamsSpec](#ccmparamsspec) used for decryption. The ciphertext is the **data** passed in for decryption. 3507- Symmetric encryption and decryption in other modes and symmetric decryption in GCM and CCM modes: The result is the complete plaintext/ciphertext. 3508 3509 (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. 3510 3511> **NOTE** 3512> 3513> 1. In symmetric encryption and decryption, after **doFinal** is called, the encryption and decryption process is complete and the [Cipher](#cipher) instance is cleared. When a new encryption and decryption process is started, **init()** must be called with a complete parameter list for initialization.<br>Even if the same symmetric key is used to encrypt and decrypt the same **Cipher** instance, the **params** parameter must be set when **init** is called during decryption. 3514> 2. If a decryption fails, check whether the data to be encrypted and decrypted matches the parameters in **init()**. For the GCM mode, check whether the **authTag** obtained after encryption is obtained from the **GcmParamsSpec** for decryption. 3515> 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. 3516> 4. For details about the sample code for calling **doFinal** multiple times in asymmetric encryption and decryption, see [Encryption and Decryption by Segment with an RSA Asymmetric Key Pair](../../security/CryptoArchitectureKit/crypto-rsa-asym-encrypt-decrypt-by-segment.md). The operations are similar for SM2 and RSA. 3517 3518**Atomic service API**: This API can be used in atomic services since API version 12. 3519 3520**System capability**: SystemCapability.Security.CryptoFramework.Cipher 3521 3522The supported system capability is SystemCapability.Security.CryptoFramework in API versions 9 to 11 and SystemCapability.Security.CryptoFramework.Cipher since API version 12. 3523 3524**Parameters** 3525 3526| Name | Type | Mandatory| Description | 3527| -------- | ------------------------------------- | ---- | ------------------------------------------------------------ | 3528| 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. | 3529| 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.| 3530 3531**Error codes** 3532For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 3533 3534| ID| Error Message | 3535| -------- | ----------------------- | 3536| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 3537| 17620001 | memory error. | 3538| 17620002 | runtime error. | 3539| 17630001 | crypto operation error. | 3540 3541**Encryption with AES GCM (example)** 3542 3543For more encryption and decryption examples, see [Encryption and Decryption with an AES Symmetric Key (GCM Mode)](../../security/CryptoArchitectureKit/crypto-aes-sym-encrypt-decrypt-gcm.md). 3544 3545```ts 3546import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 3547import { buffer } from '@kit.ArkTS'; 3548 3549function generateRandom(len: number) { 3550 let rand = cryptoFramework.createRandom(); 3551 let generateRandSync = rand.generateRandomSync(len); 3552 return generateRandSync; 3553} 3554 3555function genGcmParamsSpec() { 3556 let ivBlob = generateRandom(12); 3557 let arr = [1, 2, 3, 4, 5, 6, 7, 8]; 3558 let dataAad = new Uint8Array(arr); 3559 let aadBlob: cryptoFramework.DataBlob = { data: dataAad }; 3560 arr = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; 3561 let dataTag = new Uint8Array(arr); 3562 let tagBlob: cryptoFramework.DataBlob = { 3563 data: dataTag 3564 }; 3565 let gcmParamsSpec: cryptoFramework.GcmParamsSpec = { 3566 iv: ivBlob, 3567 aad: aadBlob, 3568 authTag: tagBlob, 3569 algName: "GcmParamsSpec" 3570 }; 3571 return gcmParamsSpec; 3572} 3573 3574function cipherByCallback() { 3575 let gcmParams = genGcmParamsSpec(); 3576 let symKeyGenerator = cryptoFramework.createSymKeyGenerator('AES128'); 3577 let cipher = cryptoFramework.createCipher('AES128|GCM|PKCS7'); 3578 symKeyGenerator.generateSymKey((err, symKey) => { 3579 cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, symKey, gcmParams, (err,) => { 3580 let message = "This is a test"; 3581 let plainText: cryptoFramework.DataBlob = { data: new Uint8Array(buffer.from(message, 'utf-8').buffer) }; 3582 cipher.update(plainText, (err, encryptUpdate) => { 3583 cipher.doFinal(null, (err, tag) => { 3584 gcmParams.authTag = tag; 3585 console.info('encryptUpdate plainText: ' + encryptUpdate.data); 3586 }); 3587 }); 3588 }); 3589 }); 3590} 3591``` 3592 3593### doFinal 3594 3595doFinal(data: DataBlob | null): Promise\<DataBlob> 3596 3597 (1) Encrypts or decrypts the remaining data (generated by the block cipher mode) and the data passed in by **doFinal()** to finalize the symmetric encryption or decryption. This API uses a promise to return the encrypted or decrypted data.<br>If a small amount of data needs to be encrypted or decrypted, you can use **doFinal()** to pass in data without using **update()**. If all the data has been passed in by **update()**, you can pass in **null** in **data** of **doFinal()**.<br>The output of **doFinal()** varies with the symmetric encryption/decryption mode in use. 3598 3599- Symmetric encryption in GCM and CCM mode: The result consists of the ciphertext and **authTag** (the last 16 bytes for GCM and the last 12 bytes for CCM). If **data** in **doFinal** is null, the result of **doFinal** is **authTag**.<br>Set **authTag** to [GcmParamsSpec](#gcmparamsspec) or [CcmParamsSpec](#ccmparamsspec) for decryption. The ciphertext is used as the input parameter **data** for decryption. 3600- Symmetric encryption and decryption in other modes and symmetric decryption in GCM and CCM modes: The result is the complete plaintext/ciphertext. 3601 3602 (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. 3603 3604> **NOTE** 3605> 3606> 1. In symmetric encryption and decryption, after **doFinal** is called, the encryption and decryption process is complete and the [Cipher](#cipher) instance is cleared. When a new encryption and decryption process is started, **init()** must be called with a complete parameter list for initialization.<br>Even if the same symmetric key is used to encrypt and decrypt the same **Cipher** instance, the **params** parameter must be set when **init** is called during decryption. 3607> 2. If a decryption fails, check whether the data to be encrypted and decrypted matches the parameters in **init()**. For the GCM mode, check whether the **authTag** obtained after encryption is obtained from the **GcmParamsSpec** for decryption. 3608> 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. 3609> 4. For details about the sample code for calling **doFinal** multiple times in asymmetric encryption and decryption, see [Encryption and Decryption by Segment with an RSA Asymmetric Key Pair](../../security/CryptoArchitectureKit/crypto-rsa-asym-encrypt-decrypt-by-segment.md). The operations are similar for SM2 and RSA. 3610 3611**Atomic service API**: This API can be used in atomic services since API version 12. 3612 3613**System capability**: SystemCapability.Security.CryptoFramework.Cipher 3614 3615The supported system capability is SystemCapability.Security.CryptoFramework in API versions 9 to 11 and SystemCapability.Security.CryptoFramework.Cipher since API version 12. 3616 3617**Parameters** 3618 3619| Name| Type | Mandatory| Description | 3620| ---- | --------------------- | ---- | -------------------- | 3621| 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.| 3622 3623**Return value** 3624 3625| Type | Description | 3626| ------------------------------- | ------------------------------------------------ | 3627| Promise\<[DataBlob](#datablob)> | Promise used to return the **DataBlob**, which is the encryption or decryption result of the remaining data.| 3628 3629**Error codes** 3630For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 3631 3632| ID| Error Message | 3633| -------- | -------------------------------------------- | 3634| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 3635| 17620001 | memory error. | 3636| 17620002 | runtime error. | 3637| 17630001 | crypto operation error. | 3638 3639**Encryption with AES GCM (example)** 3640 3641For more encryption and decryption examples, see [Encryption and Decryption with an AES Symmetric Key (GCM Mode)](../../security/CryptoArchitectureKit/crypto-aes-sym-encrypt-decrypt-gcm.md). 3642 3643```ts 3644import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 3645import { buffer } from '@kit.ArkTS'; 3646 3647function generateRandom(len: number) { 3648 let rand = cryptoFramework.createRandom(); 3649 let generateRandSync = rand.generateRandomSync(len); 3650 return generateRandSync; 3651} 3652 3653function genGcmParamsSpec() { 3654 let ivBlob = generateRandom(12); 3655 let arr = [1, 2, 3, 4, 5, 6, 7, 8]; 3656 let dataAad = new Uint8Array(arr); 3657 let aadBlob: cryptoFramework.DataBlob = { data: dataAad }; 3658 arr = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; 3659 let dataTag = new Uint8Array(arr); 3660 let tagBlob: cryptoFramework.DataBlob = { 3661 data: dataTag 3662 }; 3663 let gcmParamsSpec: cryptoFramework.GcmParamsSpec = { 3664 iv: ivBlob, 3665 aad: aadBlob, 3666 authTag: tagBlob, 3667 algName: "GcmParamsSpec" 3668 }; 3669 return gcmParamsSpec; 3670} 3671 3672async function cipherByPromise() { 3673 let gcmParams = genGcmParamsSpec(); 3674 let symKeyGenerator = cryptoFramework.createSymKeyGenerator('AES128'); 3675 let cipher = cryptoFramework.createCipher('AES128|GCM|PKCS7'); 3676 let symKey = await symKeyGenerator.generateSymKey(); 3677 await cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, symKey, gcmParams); 3678 let message = "This is a test"; 3679 let plainText: cryptoFramework.DataBlob = { data: new Uint8Array(buffer.from(message, 'utf-8').buffer) }; 3680 let encryptUpdate = await cipher.update(plainText); 3681 gcmParams.authTag = await cipher.doFinal(null); 3682 console.info('encryptUpdate plainText: ' + encryptUpdate.data); 3683} 3684``` 3685 3686### doFinalSync<sup>12+</sup> 3687 3688doFinalSync(data: DataBlob | null): DataBlob 3689 3690 (1) Encrypts or decrypts the remaining data (generated by the block cipher mode) and the data passed in by **doFinalSync()** to finalize the symmetric encryption or decryption. This API returns the result synchronously.<br>If the data volume is small, you can pass in all the data in **doFinalSync** without using **updateSync**. If data has been passed using [updateSync](#updatesync12), you can pass in **null** in **doFinalSync**.<br>The output of **doFinalSync** varies with the symmetric cipher mode in use. 3691 3692- Symmetric encryption in GCM and CCM mode: The result consists of the ciphertext and **authTag** (the last 16 bytes for GCM and the last 12 bytes for CCM). If **data** in **doFinalSync** is **null**, the result of **doFinalSync** is **authTag**.<br>Set **authTag** to [GcmParamsSpec](#gcmparamsspec) or [CcmParamsSpec](#ccmparamsspec) for decryption. The ciphertext is used as the input parameter **data** for decryption. 3693- Symmetric encryption and decryption in other modes and symmetric decryption in GCM and CCM modes: The result is the complete plaintext/ciphertext, obtained by concatenating the output of each **updateSync** and **doFinalSync**. 3694 3695 (2) Encrypts or decrypts the input data for RSA or SM2 asymmetric encryption/decryption. This API returns the result synchronously. If a large amount of data needs to be encrypted/decrypted, call **doFinalSync** multiple times and concatenate the result of each **doFinalSync** to obtain the complete plaintext/ciphertext. 3696 3697See **NOTE** in [doFinal()](#dofinal) for other precautions. 3698 3699**Atomic service API**: This API can be used in atomic services since API version 12. 3700 3701**System capability**: SystemCapability.Security.CryptoFramework.Cipher 3702 3703**Parameters** 3704 3705| Name| Type | Mandatory| Description | 3706| ------ | ------------------------------------------- | ---- | ------------------------------------------------------------ | 3707| data | [DataBlob](#datablob) | Yes | Data to encrypt or decrypt. It can be **null** in symmetric encryption or decryption, but cannot be {data:Uint8Array(empty)}.| 3708 3709**Error codes** 3710For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 3711 3712| ID| Error Message | 3713| -------- | ----------------------- | 3714| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 3715| 17620001 | memory error. | 3716| 17620002 | runtime error. | 3717| 17630001 | crypto operation error. | 3718 3719**Encryption with AES GCM (example)** 3720 3721For more encryption and decryption examples, see [Encryption and Decryption with an AES Symmetric Key (GCM Mode)](../../security/CryptoArchitectureKit/crypto-aes-sym-encrypt-decrypt-gcm.md). 3722 3723```ts 3724import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 3725import { buffer } from '@kit.ArkTS'; 3726 3727function generateRandom(len: number) { 3728 let rand = cryptoFramework.createRandom(); 3729 let generateRandSync = rand.generateRandomSync(len); 3730 return generateRandSync; 3731} 3732 3733function genGcmParamsSpec() { 3734 let ivBlob = generateRandom(12); 3735 let arr = [1, 2, 3, 4, 5, 6, 7, 8]; 3736 let dataAad = new Uint8Array(arr); 3737 let aadBlob: cryptoFramework.DataBlob = { data: dataAad }; 3738 arr = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; 3739 let dataTag = new Uint8Array(arr); 3740 let tagBlob: cryptoFramework.DataBlob = { 3741 data: dataTag 3742 }; 3743 let gcmParamsSpec: cryptoFramework.GcmParamsSpec = { 3744 iv: ivBlob, 3745 aad: aadBlob, 3746 authTag: tagBlob, 3747 algName: "GcmParamsSpec" 3748 }; 3749 return gcmParamsSpec; 3750} 3751 3752async function cipherBySync() { 3753 let gcmParams = genGcmParamsSpec(); 3754 let symKeyGenerator = cryptoFramework.createSymKeyGenerator('AES128'); 3755 let cipher = cryptoFramework.createCipher('AES128|GCM|PKCS7'); 3756 let symKey = await symKeyGenerator.generateSymKey(); 3757 await cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, symKey, gcmParams); 3758 let message = "This is a test"; 3759 let plainText: cryptoFramework.DataBlob = { data: new Uint8Array(buffer.from(message, 'utf-8').buffer) }; 3760 let encryptUpdate = cipher.updateSync(plainText); 3761 gcmParams.authTag = cipher.doFinalSync(null); 3762 console.info('encryptUpdate plainText: ' + encryptUpdate.data); 3763} 3764 3765``` 3766 3767### setCipherSpec<sup>10+</sup> 3768 3769setCipherSpec(itemType: CipherSpecItem, itemValue: Uint8Array): void 3770 3771Sets cipher specifications. You can use this API to set cipher specifications that cannot be set by [createCipher](#cryptoframeworkcreatecipher). Currently, only RSA is supported. 3772 3773**Atomic service API**: This API can be used in atomic services since API version 12. 3774 3775**System capability**: SystemCapability.Security.CryptoFramework.Cipher 3776 3777The supported system capability is SystemCapability.Security.CryptoFramework in API versions 10 to 11 and SystemCapability.Security.CryptoFramework.Cipher since API version 12. 3778 3779**Parameters** 3780 3781| Name | Type | Mandatory| Description | 3782| -------- | -------------------- | ---- | ---------- | 3783| itemType | [CipherSpecItem](#cipherspecitem10) | Yes | Cipher parameter to set.| 3784| itemValue | Uint8Array | Yes | Value of the parameter to set.| 3785 3786**Error codes** 3787For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 3788 3789| ID| Error Message | 3790| -------- | ---------------------- | 3791| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 3792| 801 | this operation is not supported. | 3793| 17620001 | memory error. | 3794| 17630001 | crypto operation error. | 3795 3796**Example** 3797 3798<!--code_no_check--> 3799```ts 3800let cipher: cryptoFramework.Cipher; // The process of generating the Cipher instance is omitted here. 3801let pSource = new Uint8Array([1,2,3,4]); 3802cipher.setCipherSpec(cryptoFramework.CipherSpecItem.OAEP_MGF1_PSRC_UINT8ARR, pSource); 3803``` 3804 3805### getCipherSpec<sup>10+</sup> 3806 3807getCipherSpec(itemType: CipherSpecItem): string | Uint8Array 3808 3809Obtains cipher specifications. Currently, only RSA and SM2 (available since API version 11) are supported. 3810 3811**Atomic service API**: This API can be used in atomic services since API version 12. 3812 3813**System capability**: SystemCapability.Security.CryptoFramework.Cipher 3814 3815The supported system capability is SystemCapability.Security.CryptoFramework in API versions 10 to 11 and SystemCapability.Security.CryptoFramework.Cipher since API version 12. 3816 3817**Parameters** 3818 3819| Name| Type | Mandatory| Description | 3820| ------ | -------- | ---- | ---------- | 3821| itemType | [CipherSpecItem](#cipherspecitem10) | Yes | Cipher parameter to obtain.| 3822 3823**Return value** 3824 3825| Type | Description | 3826| -------------- | ----------- | 3827| string \| Uint8Array | Returns the value of the cipher parameter obtained.| 3828 3829**Error codes** 3830For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 3831 3832| ID| Error Message | 3833| -------- | ---------------------- | 3834| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 3835| 801 | this operation is not supported. | 3836| 17620001 | memory error. | 3837| 17630001 | crypto operation error. | 3838 3839**Example** 3840 3841<!--code_no_check--> 3842```ts 3843let cipher: cryptoFramework.Cipher; // The process of generating the Cipher instance is omitted here. 3844let mdName = cipher.getCipherSpec(cryptoFramework.CipherSpecItem.OAEP_MD_NAME_STR); 3845``` 3846 3847## cryptoFramework.createSign 3848 3849createSign(algName: string): Sign 3850 3851Creates a **Sign** instance. 3852 3853For details about the supported specifications, see [Signing and Signature Verification Overview and Algorithm Specifications](../../security/CryptoArchitectureKit/crypto-sign-sig-verify-overview.md). 3854 3855**Atomic service API**: This API can be used in atomic services since API version 12. 3856 3857**System capability**: SystemCapability.Security.CryptoFramework.Signature 3858 3859The supported system capability is SystemCapability.Security.CryptoFramework in API versions 9 to 11 and SystemCapability.Security.CryptoFramework.Signature since API version 12. 3860 3861**Parameters** 3862 3863| Name | Type | Mandatory| Description | 3864| ------- | ------ | ---- | ------------------------------------------------------------ | 3865| algName | string | Yes | Signing algorithm to use. Currently, RSA, ECC, DSA, SM2<sup>10+</sup> and Ed25519<sup>11+</sup> are supported. <br>If the RSA PKCS1 mode is used, you need to set the digest. If the RSA PSS mode is used, you need to set the digest and mask digest.<br>When RSA is used for signing, you can set **OnlySign** to enable the input data digest to be used only for signing.| 3866 3867**Return value** 3868 3869| Type| Description | 3870| ---- | ---------------------------------- | 3871| Sign | Returns the **Sign** instance created.| 3872 3873**Error codes** 3874For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 3875 3876| ID| Error Message | 3877| -------- | ---------------------- | 3878| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 3879| 801 | this operation is not supported. | 3880| 17620001 | memory error. | 3881 3882**Example** 3883 3884```ts 3885import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 3886 3887let signer1 = cryptoFramework.createSign('RSA1024|PKCS1|SHA256'); 3888 3889let signer2 = cryptoFramework.createSign('RSA1024|PSS|SHA256|MGF1_SHA256'); 3890 3891let signer3 = cryptoFramework.createSign('ECC224|SHA256'); 3892 3893let signer4 = cryptoFramework.createSign('DSA2048|SHA256'); 3894 3895let signer5 = cryptoFramework.createSign('RSA1024|PKCS1|SHA256|OnlySign'); 3896``` 3897 3898## Sign 3899 3900Provides APIs for signing. Before using any API of the **Sign** class, you must create a **Sign** instance by using [createSign(algName: string): Sign](#cryptoframeworkcreatesign). Invoke **init()**, **update()**, and **sign()** in this class in sequence to complete the signing operation. For details about the sample code, see [Signing and Signature Verification with an RSA Key Pair (PKCS1 Mode)](../../security/CryptoArchitectureKit/crypto-rsa-sign-sig-verify-pkcs1.md). 3901 3902The **Sign** class does not support repeated initialization. When a new key is used for signing, you must create a new **Sign** instance and call **init()** for initialization. 3903 3904The signing mode is determined in **createSign()**, and the key is set by **init()**. 3905 3906If 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()**. 3907 3908If 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. 3909 3910When **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. 3911 3912If the DSA algorithm is used for signing and the digest algorithm is **NoHash**, **update()** is not supported. If **update()** is called in this case, **ERR_CRYPTO_OPERATION** will be returned. 3913 3914### Attributes 3915 3916**Atomic service API**: This API can be used in atomic services since API version 12. 3917 3918**System capability**: SystemCapability.Security.CryptoFramework.Signature 3919 3920The supported system capability is SystemCapability.Security.CryptoFramework in API versions 9 to 11 and SystemCapability.Security.CryptoFramework.Signature since API version 12. 3921 3922| Name | Type | Readable| Writable| Description | 3923| ------- | ------ | ---- | ---- | ---------------------------- | 3924| algName | string | Yes | No | Algorithm to use.| 3925 3926### init 3927 3928init(priKey: PriKey, callback: AsyncCallback\<void>): void 3929 3930Initializes the **Sign** instance with a private key. This API uses an asynchronous callback to return the result. **init**, **update**, and **sign** must be used together. **init** and **sign** are mandatory, and **update** is optional. 3931 3932The **Sign** class does not support repeated use of **init()**. 3933 3934**Atomic service API**: This API can be used in atomic services since API version 12. 3935 3936**System capability**: SystemCapability.Security.CryptoFramework.Signature 3937 3938The supported system capability is SystemCapability.Security.CryptoFramework in API versions 9 to 11 and SystemCapability.Security.CryptoFramework.Signature since API version 12. 3939 3940**Parameters** 3941 3942| Name | Type | Mandatory| Description | 3943| -------- | -------------------- | ---- | ---------------- | 3944| priKey | [PriKey](#prikey) | Yes | Private key used for the initialization.| 3945| callback | AsyncCallback\<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.| 3946 3947**Error codes** 3948For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 3949 3950| ID| Error Message | 3951| -------- | ---------------------- | 3952| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 3953| 17620001 | memory error. | 3954| 17620002 | runtime error. | 3955| 17630001 | crypto operation error. | 3956 3957### init 3958 3959init(priKey: PriKey): Promise\<void> 3960 3961Initializes the **Sign** instance with a private key. This API uses a promise to return the result. **init**, **update**, and **sign** must be used together. **init** and **sign** are mandatory, and **update** is optional. 3962 3963The **Sign** class does not support repeated use of **init()**. 3964 3965**Atomic service API**: This API can be used in atomic services since API version 12. 3966 3967**System capability**: SystemCapability.Security.CryptoFramework.Signature 3968 3969The supported system capability is SystemCapability.Security.CryptoFramework in API versions 9 to 11 and SystemCapability.Security.CryptoFramework.Signature since API version 12. 3970 3971**Parameters** 3972 3973| Name| Type| Mandatory| Description | 3974| ------ | ---- | ---- | ---------------- | 3975| priKey | [PriKey](#prikey) | Yes | Private key used for the initialization.| 3976 3977**Return value** 3978 3979| Type | Description | 3980| -------------- | ------------- | 3981| Promise\<void> | Promise that returns no value.| 3982 3983**Error codes** 3984For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 3985 3986| ID| Error Message | 3987| -------- | ---------------------- | 3988| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 3989| 17620001 | memory error. | 3990| 17620002 | runtime error. | 3991| 17630001 | crypto operation error. | 3992 3993### initSync<sup>12+</sup> 3994 3995initSync(priKey: PriKey): void 3996 3997Initializes the **Sign** instance with a private key. This API returns the result synchronously. **initSync**, **updateSync**, and **signSync** must be used together. **initSync** and **signSync** are mandatory, and **updateSync** is optional. 3998 3999The **Sign** class does not support repeated use of **initSync()**. 4000 4001**Atomic service API**: This API can be used in atomic services since API version 12. 4002 4003**System capability**: SystemCapability.Security.CryptoFramework.Signature 4004 4005**Parameters** 4006 4007| Name| Type| Mandatory| Description | 4008| ------ | ---- | ---- | ---------------- | 4009| priKey | [PriKey](#prikey) | Yes | Private key used for the initialization.| 4010 4011**Error codes** 4012For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 4013 4014| ID| Error Message | 4015| -------- | ---------------------- | 4016| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 4017| 17620001 | memory error. | 4018| 17620002 | runtime error. | 4019| 17630001 | crypto operation error. | 4020 4021### update 4022 4023update(data: DataBlob, callback: AsyncCallback\<void>): void 4024 4025Updates the data to be signed. This API uses an asynchronous callback to return the result. 4026 4027This API can be called only after the [Sign](#sign) instance is initialized by using [init()](#init-2). 4028 4029> **NOTE** 4030> 4031> You can call **update** multiple times or do not use **update** (call [sign](#sign-1) after [init](#init-2)), depending on the data volume.<br> 4032> The amount of the data to be passed in by **update()** (one-time or accumulative) is not limited. If there is a large amount of data, you are advised to call **update()** multiple times to pass in the data by segment. This prevents too much memory from being requested at a time.<br> 4033> For details about the sample code for calling **update()** multiple times in signing, see [Signing and Signature Verification by Segment with an RSA Key Pair (PKCS1 Mode)](../../security/CryptoArchitectureKit/crypto-rsa-sign-sig-verify-pkcs1-by-segment.md). The operations of other algorithms are similar.<br> 4034> **OnlySign** cannot be used with **update()**. If **OnlySign** is specified, use **sign()** to pass in data.<br> 4035> If the DSA algorithm is used for signing and the digest algorithm is **NoHash**, **update()** is not supported. If **update()** is called in this case, **ERR_CRYPTO_OPERATION** will be returned. 4036 4037**Atomic service API**: This API can be used in atomic services since API version 12. 4038 4039**System capability**: SystemCapability.Security.CryptoFramework.Signature 4040 4041The supported system capability is SystemCapability.Security.CryptoFramework in API versions 9 to 11 and SystemCapability.Security.CryptoFramework.Signature since API version 12. 4042 4043**Parameters** 4044 4045| Name | Type | Mandatory| Description | 4046| -------- | --------------------- | ---- | ------------ | 4047| data | [DataBlob](#datablob) | Yes | Data to pass in.| 4048| callback | AsyncCallback\<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.| 4049 4050**Error codes** 4051For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 4052 4053| ID| Error Message | 4054| -------- | ---------------------- | 4055| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 4056| 17620001 | memory error. | 4057| 17620002 | runtime error. | 4058| 17630001 | crypto operation error. | 4059 4060### update 4061 4062update(data: DataBlob): Promise\<void> 4063 4064Updates the data to be signed. This API uses a promise to return the result. 4065 4066This API can be called only after the [Sign](#sign) instance is initialized by using [init()](#init-3). 4067 4068> **NOTE** 4069> 4070> You can call **update** multiple times or do not use **update** (call [sign](#sign-2) after [init](#init-3)), depending on the data volume.<br> 4071> The amount of the data to be passed in by **update()** (one-time or accumulative) is not limited. If there is a large amount of data, you are advised to call **update()** multiple times to pass in the data by segment. This prevents too much memory from being requested at a time.<br> 4072> For details about the sample code for calling **update()** multiple times in signing, see [Signing and Signature Verification by Segment with an RSA Key Pair (PKCS1 Mode)](../../security/CryptoArchitectureKit/crypto-rsa-sign-sig-verify-pkcs1-by-segment.md). The operations of other algorithms are similar.<br> 4073> **OnlySign** cannot be used with **update()**. If **OnlySign** is specified, use **sign()** to pass in data.<br> 4074> If the DSA algorithm is used for signing and the digest algorithm is **NoHash**, **update()** is not supported. If **update()** is called in this case, **ERR_CRYPTO_OPERATION** will be returned. 4075 4076**Atomic service API**: This API can be used in atomic services since API version 12. 4077 4078**System capability**: SystemCapability.Security.CryptoFramework.Signature 4079 4080The supported system capability is SystemCapability.Security.CryptoFramework in API versions 9 to 11 and SystemCapability.Security.CryptoFramework.Signature since API version 12. 4081 4082**Parameters** 4083 4084| Name| Type | Mandatory| Description | 4085| ------ | -------- | ---- | ---------- | 4086| data | [DataBlob](#datablob) | Yes | Data to pass in.| 4087 4088**Return value** 4089 4090| Type | Description | 4091| -------------- | ------------- | 4092| Promise\<void> | Promise that returns no value.| 4093 4094**Error codes** 4095For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 4096 4097| ID| Error Message | 4098| -------- | ---------------------- | 4099| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 4100| 17620001 | memory error. | 4101| 17620002 | runtime error. | 4102| 17630001 | crypto operation error. | 4103 4104### updateSync<sup>12+</sup> 4105 4106updateSync(data: DataBlob): void 4107 4108Updates the data to be signed. This API returns the result synchronously. 4109 4110This API can be called only after the [Sign](#sign) instance is initialized by using [initSync()](#initsync12-1). 4111 4112> **NOTE** 4113> 4114> You can call **updateSync** multiple times or do not use **updateSync** (call [signSync](#signsync12) after [initSync](#initsync12-1)), depending on the data volume.<br> 4115> The amount of the data to be passed in by **updateSync** (one-time or accumulative) is not limited. If there is a large amount of data, you are advised to call **updateSync** multiple times to pass in the data by segment. This prevents too much memory from being requested at a time.<br> 4116> For details about the sample code for calling **updateSync** multiple times in signing, see [Signing and Signature Verification by Segment with an RSA Key Pair (PKCS1 Mode)](../../security/CryptoArchitectureKit/crypto-rsa-sign-sig-verify-pkcs1-by-segment.md). The operations of other algorithms are similar.<br> 4117> **OnlySign** cannot be used with **updateSync**. If **OnlySign** is specified, use **signSync** to pass in data.<br> 4118> If the DSA algorithm is used for signing and the digest algorithm is **NoHash**, **updateSync** is not supported. If **updateSync** is called in this case, **ERR_CRYPTO_OPERATION** will be returned. 4119 4120**Atomic service API**: This API can be used in atomic services since API version 12. 4121 4122**System capability**: SystemCapability.Security.CryptoFramework.Signature 4123 4124**Parameters** 4125 4126| Name| Type | Mandatory| Description | 4127| ------ | -------- | ---- | ---------- | 4128| data | [DataBlob](#datablob) | Yes | Data to pass in.| 4129 4130**Return value** 4131 4132| Type | Description | 4133| -------------- | ------------- | 4134| void | No value is returned.| 4135 4136**Error codes** 4137For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 4138 4139| ID| Error Message | 4140| -------- | ---------------------- | 4141| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 4142| 17620001 | memory error. | 4143| 17620002 | runtime error. | 4144| 17630001 | crypto operation error. | 4145 4146### sign 4147 4148sign(data: DataBlob | null, callback: AsyncCallback\<DataBlob>): void 4149 4150Signs the data. This API uses an asynchronous callback to return the result. 4151 4152**Atomic service API**: This API can be used in atomic services since API version 12. 4153 4154**System capability**: SystemCapability.Security.CryptoFramework.Signature 4155 4156The supported system capability is SystemCapability.Security.CryptoFramework in API versions 9 to 11 and SystemCapability.Security.CryptoFramework.Signature since API version 12. 4157 4158**Parameters** 4159 4160| Name | Type | Mandatory| Description | 4161| -------- | -------------------- | ---- | ---------- | 4162| 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.| 4163| callback | AsyncCallback\<[DataBlob](#datablob)> | Yes | Callback invoked to return a **DataBlob** object.| 4164 4165**Error codes** 4166For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 4167 4168| ID| Error Message | 4169| -------- | ---------------------- | 4170| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 4171| 17620001 | memory error. | 4172| 17620002 | runtime error. | 4173| 17630001 | crypto operation error. | 4174 4175### sign 4176 4177sign(data: DataBlob | null): Promise\<DataBlob> 4178 4179Signs the data. This API uses a promise to return the result. 4180 4181**Atomic service API**: This API can be used in atomic services since API version 12. 4182 4183**System capability**: SystemCapability.Security.CryptoFramework.Signature 4184 4185The supported system capability is SystemCapability.Security.CryptoFramework in API versions 9 to 11 and SystemCapability.Security.CryptoFramework.Signature since API version 12. 4186 4187**Parameters** 4188 4189| Name| Type | Mandatory| Description | 4190| ------ | -------- | ---- | ---------- | 4191| data | [DataBlob](#datablob) \| null<sup>10+</sup> | Yes | Data to pass in.| 4192 4193**Return value** 4194 4195| Type | Description | 4196| -------------- | ------------- | 4197| Promise\<[DataBlob](#datablob)> | Promise used to return the signature.| 4198 4199**Error codes** 4200For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 4201 4202| ID| Error Message | 4203| -------- | ---------------------- | 4204| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 4205| 17620001 | memory error. | 4206| 17620002 | runtime error. | 4207| 17630001 | crypto operation error. | 4208 4209### signSync<sup>12+</sup> 4210 4211signSync(data: DataBlob | null): DataBlob 4212 4213Signs the data. This API returns the result synchronously. 4214 4215**Atomic service API**: This API can be used in atomic services since API version 12. 4216 4217**System capability**: SystemCapability.Security.CryptoFramework.Signature 4218 4219**Parameters** 4220 4221| Name| Type | Mandatory| Description | 4222| ------ | -------- | ---- | ---------- | 4223| data | [DataBlob](#datablob) \| null | Yes | Data to pass in.| 4224 4225**Return value** 4226 4227| Type | Description | 4228| -------------- | ------------- | 4229| [DataBlob](#datablob) | Signature.| 4230 4231**Error codes** 4232For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 4233 4234| ID| Error Message | 4235| -------- | ---------------------- | 4236| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 4237| 17620001 | memory error. | 4238| 17620002 | runtime error. | 4239| 17630001 | crypto operation error. | 4240 4241**Example (using the callback-based API)** 4242 4243For more examples of signing and signature verification, see [Signing and Signature Verification with an RSA Key Pair (PKCS1 Mode)](../../security/CryptoArchitectureKit/crypto-rsa-sign-sig-verify-pkcs1.md). 4244 4245```ts 4246import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 4247import { buffer } from '@kit.ArkTS'; 4248 4249function signByCallback() { 4250 let inputUpdate: cryptoFramework.DataBlob = { data: new Uint8Array(buffer.from("This is Sign test plan1", 'utf-8').buffer) }; 4251 let inputVerify: cryptoFramework.DataBlob = { data: new Uint8Array(buffer.from("This is Sign test plan2", 'utf-8').buffer) }; 4252 let pkData = new Uint8Array([48, 129, 159, 48, 13, 6, 9, 42, 134, 72, 134, 247, 13, 1, 1, 1, 5, 0, 3, 129, 141, 0, 48, 129, 137, 2, 129, 129, 0, 214, 179, 23, 198, 183, 139, 148, 8, 173, 74, 56, 160, 15, 248, 244, 166, 209, 250, 142, 74, 216, 58, 117, 215, 178, 247, 254, 39, 180, 227, 85, 201, 59, 133, 209, 221, 26, 9, 116, 31, 172, 151, 252, 185, 123, 20, 25, 7, 92, 129, 5, 196, 239, 214, 126, 254, 154, 188, 239, 144, 161, 171, 65, 42, 31, 214, 93, 115, 247, 69, 94, 143, 54, 51, 25, 49, 146, 204, 205, 165, 20, 120, 35, 184, 190, 65, 106, 12, 214, 176, 57, 125, 235, 51, 88, 135, 76, 73, 109, 112, 147, 138, 198, 252, 5, 20, 245, 51, 7, 32, 108, 89, 125, 204, 50, 189, 88, 254, 255, 146, 244, 244, 149, 79, 54, 216, 45, 89, 2, 3, 1, 0, 1]); 4253 let skData = new Uint8Array([48, 130, 2, 120, 2, 1, 0, 48, 13, 6, 9, 42, 134, 72, 134, 247, 13, 1, 1, 1, 5, 0, 4, 130, 2, 98, 48, 130, 2, 94, 2, 1, 0, 2, 129, 129, 0, 214, 179, 23, 198, 183, 139, 148, 8, 173, 74, 56, 160, 15, 248, 244, 166, 209, 250, 142, 74, 216, 58, 117, 215, 178, 247, 254, 39, 180, 227, 85, 201, 59, 133, 209, 221, 26, 9, 116, 31, 172, 151, 252, 185, 123, 20, 25, 7, 92, 129, 5, 196, 239, 214, 126, 254, 154, 188, 239, 144, 161, 171, 65, 42, 31, 214, 93, 115, 247, 69, 94, 143, 54, 51, 25, 49, 146, 204, 205, 165, 20, 120, 35, 184, 190, 65, 106, 12, 214, 176, 57, 125, 235, 51, 88, 135, 76, 73, 109, 112, 147, 138, 198, 252, 5, 20, 245, 51, 7, 32, 108, 89, 125, 204, 50, 189, 88, 254, 255, 146, 244, 244, 149, 79, 54, 216, 45, 89, 2, 3, 1, 0, 1, 2, 129, 129, 0, 152, 111, 145, 203, 10, 88, 116, 163, 112, 126, 9, 20, 68, 34, 235, 121, 98, 14, 182, 102, 151, 125, 114, 91, 210, 122, 215, 29, 212, 5, 176, 203, 238, 146, 5, 190, 41, 21, 91, 56, 125, 239, 111, 133, 53, 200, 192, 56, 132, 202, 42, 145, 120, 3, 224, 40, 223, 46, 148, 29, 41, 92, 17, 40, 12, 72, 165, 69, 192, 211, 142, 233, 81, 202, 177, 235, 156, 27, 179, 48, 18, 85, 154, 101, 193, 45, 218, 91, 24, 143, 196, 248, 16, 83, 177, 198, 136, 77, 111, 134, 60, 219, 95, 246, 23, 5, 45, 14, 83, 29, 137, 248, 159, 28, 132, 142, 205, 99, 226, 213, 84, 232, 57, 130, 156, 81, 191, 237, 2, 65, 0, 255, 158, 212, 13, 43, 132, 244, 135, 148, 161, 232, 219, 20, 81, 196, 102, 103, 44, 110, 71, 100, 62, 73, 200, 32, 138, 114, 209, 171, 150, 179, 92, 198, 5, 190, 218, 79, 227, 227, 37, 32, 57, 159, 252, 107, 211, 139, 198, 202, 248, 137, 143, 186, 205, 106, 81, 85, 207, 134, 148, 110, 204, 243, 27, 2, 65, 0, 215, 4, 181, 121, 57, 224, 170, 168, 183, 159, 152, 8, 74, 233, 80, 244, 146, 81, 48, 159, 194, 199, 36, 187, 6, 181, 182, 223, 115, 133, 151, 171, 78, 219, 90, 161, 248, 69, 6, 207, 173, 3, 81, 161, 2, 60, 238, 204, 177, 12, 138, 17, 220, 179, 71, 113, 200, 248, 159, 153, 252, 150, 180, 155, 2, 65, 0, 190, 202, 185, 211, 170, 171, 238, 40, 84, 84, 21, 13, 144, 57, 7, 178, 183, 71, 126, 120, 98, 229, 235, 4, 40, 229, 173, 149, 185, 209, 29, 199, 29, 54, 164, 161, 38, 8, 30, 62, 83, 179, 47, 42, 165, 0, 156, 207, 160, 39, 169, 229, 81, 180, 136, 170, 116, 182, 20, 233, 45, 90, 100, 9, 2, 65, 0, 152, 255, 47, 198, 15, 201, 238, 133, 89, 11, 133, 153, 184, 252, 37, 239, 177, 65, 118, 80, 231, 190, 222, 66, 250, 118, 72, 166, 221, 67, 156, 245, 119, 138, 28, 6, 142, 107, 71, 122, 116, 200, 156, 199, 237, 152, 191, 239, 4, 184, 64, 114, 143, 81, 62, 48, 23, 233, 217, 95, 47, 221, 104, 171, 2, 64, 30, 219, 1, 230, 241, 70, 246, 243, 121, 174, 67, 66, 11, 99, 202, 17, 52, 234, 78, 29, 3, 57, 51, 123, 149, 86, 64, 192, 73, 199, 108, 101, 55, 232, 41, 114, 153, 237, 253, 52, 205, 148, 45, 86, 186, 241, 182, 183, 42, 77, 252, 195, 29, 158, 173, 3, 182, 207, 254, 61, 71, 184, 167, 184]); 4254 let pubKeyBlob: cryptoFramework.DataBlob = { data: pkData }; 4255 let priKeyBlob: cryptoFramework.DataBlob = { data: skData }; 4256 let rsaGenerator = cryptoFramework.createAsyKeyGenerator('RSA1024'); 4257 let signer = cryptoFramework.createSign('RSA1024|PKCS1|SHA256'); 4258 rsaGenerator.convertKey(pubKeyBlob, priKeyBlob, (err, keyPair) => { 4259 signer.init(keyPair.priKey, err => { 4260 signer.update(inputUpdate, err => { 4261 signer.sign(inputVerify, (err, signData) => { 4262 console.info('sign output is ' + signData.data); 4263 }); 4264 }); 4265 }); 4266 }); 4267} 4268``` 4269 4270**Example (using the promise-based API)** 4271 4272For more examples of signing and signature verification, see [Signing and Signature Verification with an RSA Key Pair (PKCS1 Mode)](../../security/CryptoArchitectureKit/crypto-rsa-sign-sig-verify-pkcs1.md). 4273 4274```ts 4275import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 4276import { buffer } from '@kit.ArkTS'; 4277 4278async function genKeyPairByData(pubKeyData: Uint8Array, priKeyData: Uint8Array) { 4279 let pubKeyBlob: cryptoFramework.DataBlob = { data: pubKeyData }; 4280 let priKeyBlob: cryptoFramework.DataBlob = { data: priKeyData }; 4281 let rsaGenerator = cryptoFramework.createAsyKeyGenerator('RSA1024'); 4282 let keyPair = await rsaGenerator.convertKey(pubKeyBlob, priKeyBlob); 4283 console.info('convertKey success'); 4284 return keyPair; 4285} 4286 4287async function signByPromise() { 4288 let pkData = new Uint8Array([48, 129, 159, 48, 13, 6, 9, 42, 134, 72, 134, 247, 13, 1, 1, 1, 5, 0, 3, 129, 141, 0, 48, 129, 137, 2, 129, 129, 0, 214, 179, 23, 198, 183, 139, 148, 8, 173, 74, 56, 160, 15, 248, 244, 166, 209, 250, 142, 74, 216, 58, 117, 215, 178, 247, 254, 39, 180, 227, 85, 201, 59, 133, 209, 221, 26, 9, 116, 31, 172, 151, 252, 185, 123, 20, 25, 7, 92, 129, 5, 196, 239, 214, 126, 254, 154, 188, 239, 144, 161, 171, 65, 42, 31, 214, 93, 115, 247, 69, 94, 143, 54, 51, 25, 49, 146, 204, 205, 165, 20, 120, 35, 184, 190, 65, 106, 12, 214, 176, 57, 125, 235, 51, 88, 135, 76, 73, 109, 112, 147, 138, 198, 252, 5, 20, 245, 51, 7, 32, 108, 89, 125, 204, 50, 189, 88, 254, 255, 146, 244, 244, 149, 79, 54, 216, 45, 89, 2, 3, 1, 0, 1]); 4289 let skData = new Uint8Array([48, 130, 2, 120, 2, 1, 0, 48, 13, 6, 9, 42, 134, 72, 134, 247, 13, 1, 1, 1, 5, 0, 4, 130, 2, 98, 48, 130, 2, 94, 2, 1, 0, 2, 129, 129, 0, 214, 179, 23, 198, 183, 139, 148, 8, 173, 74, 56, 160, 15, 248, 244, 166, 209, 250, 142, 74, 216, 58, 117, 215, 178, 247, 254, 39, 180, 227, 85, 201, 59, 133, 209, 221, 26, 9, 116, 31, 172, 151, 252, 185, 123, 20, 25, 7, 92, 129, 5, 196, 239, 214, 126, 254, 154, 188, 239, 144, 161, 171, 65, 42, 31, 214, 93, 115, 247, 69, 94, 143, 54, 51, 25, 49, 146, 204, 205, 165, 20, 120, 35, 184, 190, 65, 106, 12, 214, 176, 57, 125, 235, 51, 88, 135, 76, 73, 109, 112, 147, 138, 198, 252, 5, 20, 245, 51, 7, 32, 108, 89, 125, 204, 50, 189, 88, 254, 255, 146, 244, 244, 149, 79, 54, 216, 45, 89, 2, 3, 1, 0, 1, 2, 129, 129, 0, 152, 111, 145, 203, 10, 88, 116, 163, 112, 126, 9, 20, 68, 34, 235, 121, 98, 14, 182, 102, 151, 125, 114, 91, 210, 122, 215, 29, 212, 5, 176, 203, 238, 146, 5, 190, 41, 21, 91, 56, 125, 239, 111, 133, 53, 200, 192, 56, 132, 202, 42, 145, 120, 3, 224, 40, 223, 46, 148, 29, 41, 92, 17, 40, 12, 72, 165, 69, 192, 211, 142, 233, 81, 202, 177, 235, 156, 27, 179, 48, 18, 85, 154, 101, 193, 45, 218, 91, 24, 143, 196, 248, 16, 83, 177, 198, 136, 77, 111, 134, 60, 219, 95, 246, 23, 5, 45, 14, 83, 29, 137, 248, 159, 28, 132, 142, 205, 99, 226, 213, 84, 232, 57, 130, 156, 81, 191, 237, 2, 65, 0, 255, 158, 212, 13, 43, 132, 244, 135, 148, 161, 232, 219, 20, 81, 196, 102, 103, 44, 110, 71, 100, 62, 73, 200, 32, 138, 114, 209, 171, 150, 179, 92, 198, 5, 190, 218, 79, 227, 227, 37, 32, 57, 159, 252, 107, 211, 139, 198, 202, 248, 137, 143, 186, 205, 106, 81, 85, 207, 134, 148, 110, 204, 243, 27, 2, 65, 0, 215, 4, 181, 121, 57, 224, 170, 168, 183, 159, 152, 8, 74, 233, 80, 244, 146, 81, 48, 159, 194, 199, 36, 187, 6, 181, 182, 223, 115, 133, 151, 171, 78, 219, 90, 161, 248, 69, 6, 207, 173, 3, 81, 161, 2, 60, 238, 204, 177, 12, 138, 17, 220, 179, 71, 113, 200, 248, 159, 153, 252, 150, 180, 155, 2, 65, 0, 190, 202, 185, 211, 170, 171, 238, 40, 84, 84, 21, 13, 144, 57, 7, 178, 183, 71, 126, 120, 98, 229, 235, 4, 40, 229, 173, 149, 185, 209, 29, 199, 29, 54, 164, 161, 38, 8, 30, 62, 83, 179, 47, 42, 165, 0, 156, 207, 160, 39, 169, 229, 81, 180, 136, 170, 116, 182, 20, 233, 45, 90, 100, 9, 2, 65, 0, 152, 255, 47, 198, 15, 201, 238, 133, 89, 11, 133, 153, 184, 252, 37, 239, 177, 65, 118, 80, 231, 190, 222, 66, 250, 118, 72, 166, 221, 67, 156, 245, 119, 138, 28, 6, 142, 107, 71, 122, 116, 200, 156, 199, 237, 152, 191, 239, 4, 184, 64, 114, 143, 81, 62, 48, 23, 233, 217, 95, 47, 221, 104, 171, 2, 64, 30, 219, 1, 230, 241, 70, 246, 243, 121, 174, 67, 66, 11, 99, 202, 17, 52, 234, 78, 29, 3, 57, 51, 123, 149, 86, 64, 192, 73, 199, 108, 101, 55, 232, 41, 114, 153, 237, 253, 52, 205, 148, 45, 86, 186, 241, 182, 183, 42, 77, 252, 195, 29, 158, 173, 3, 182, 207, 254, 61, 71, 184, 167, 184]); 4290 let keyPair = await genKeyPairByData(pkData, skData); 4291 let inputUpdate: cryptoFramework.DataBlob = { data: new Uint8Array(buffer.from("This is Sign test plan1", 'utf-8').buffer) }; 4292 let inputSign: cryptoFramework.DataBlob = { data: new Uint8Array(buffer.from("This is Sign test plan2", 'utf-8').buffer) }; 4293 let signer = cryptoFramework.createSign('RSA1024|PKCS1|SHA256'); 4294 await signer.init(keyPair.priKey); 4295 await signer.update(inputUpdate); 4296 let signData = await signer.sign(inputSign); 4297 console.info('signData result: ' + signData.data); 4298} 4299``` 4300 4301**Example (using the sync API)** 4302 4303For more examples of signing and signature verification, see [Signing and Signature Verification with an RSA Key Pair (PKCS1 Mode)](../../security/CryptoArchitectureKit/crypto-rsa-sign-sig-verify-pkcs1.md). 4304 4305```ts 4306import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 4307import { buffer } from '@kit.ArkTS'; 4308 4309function genKeyPairByData(pubKeyData: Uint8Array, priKeyData: Uint8Array) { 4310 let pubKeyBlob: cryptoFramework.DataBlob = { data: pubKeyData }; 4311 let priKeyBlob: cryptoFramework.DataBlob = { data: priKeyData }; 4312 let rsaGenerator = cryptoFramework.createAsyKeyGenerator('RSA1024'); 4313 let keyPair = rsaGenerator.convertKeySync(pubKeyBlob, priKeyBlob); 4314 console.info('convertKeySync success'); 4315 return keyPair; 4316} 4317 4318function signBySync() { 4319 let pkData = new Uint8Array([48, 129, 159, 48, 13, 6, 9, 42, 134, 72, 134, 247, 13, 1, 1, 1, 5, 0, 3, 129, 141, 0, 48, 129, 137, 2, 129, 129, 0, 214, 179, 23, 198, 183, 139, 148, 8, 173, 74, 56, 160, 15, 248, 244, 166, 209, 250, 142, 74, 216, 58, 117, 215, 178, 247, 254, 39, 180, 227, 85, 201, 59, 133, 209, 221, 26, 9, 116, 31, 172, 151, 252, 185, 123, 20, 25, 7, 92, 129, 5, 196, 239, 214, 126, 254, 154, 188, 239, 144, 161, 171, 65, 42, 31, 214, 93, 115, 247, 69, 94, 143, 54, 51, 25, 49, 146, 204, 205, 165, 20, 120, 35, 184, 190, 65, 106, 12, 214, 176, 57, 125, 235, 51, 88, 135, 76, 73, 109, 112, 147, 138, 198, 252, 5, 20, 245, 51, 7, 32, 108, 89, 125, 204, 50, 189, 88, 254, 255, 146, 244, 244, 149, 79, 54, 216, 45, 89, 2, 3, 1, 0, 1]); 4320 let skData = new Uint8Array([48, 130, 2, 120, 2, 1, 0, 48, 13, 6, 9, 42, 134, 72, 134, 247, 13, 1, 1, 1, 5, 0, 4, 130, 2, 98, 48, 130, 2, 94, 2, 1, 0, 2, 129, 129, 0, 214, 179, 23, 198, 183, 139, 148, 8, 173, 74, 56, 160, 15, 248, 244, 166, 209, 250, 142, 74, 216, 58, 117, 215, 178, 247, 254, 39, 180, 227, 85, 201, 59, 133, 209, 221, 26, 9, 116, 31, 172, 151, 252, 185, 123, 20, 25, 7, 92, 129, 5, 196, 239, 214, 126, 254, 154, 188, 239, 144, 161, 171, 65, 42, 31, 214, 93, 115, 247, 69, 94, 143, 54, 51, 25, 49, 146, 204, 205, 165, 20, 120, 35, 184, 190, 65, 106, 12, 214, 176, 57, 125, 235, 51, 88, 135, 76, 73, 109, 112, 147, 138, 198, 252, 5, 20, 245, 51, 7, 32, 108, 89, 125, 204, 50, 189, 88, 254, 255, 146, 244, 244, 149, 79, 54, 216, 45, 89, 2, 3, 1, 0, 1, 2, 129, 129, 0, 152, 111, 145, 203, 10, 88, 116, 163, 112, 126, 9, 20, 68, 34, 235, 121, 98, 14, 182, 102, 151, 125, 114, 91, 210, 122, 215, 29, 212, 5, 176, 203, 238, 146, 5, 190, 41, 21, 91, 56, 125, 239, 111, 133, 53, 200, 192, 56, 132, 202, 42, 145, 120, 3, 224, 40, 223, 46, 148, 29, 41, 92, 17, 40, 12, 72, 165, 69, 192, 211, 142, 233, 81, 202, 177, 235, 156, 27, 179, 48, 18, 85, 154, 101, 193, 45, 218, 91, 24, 143, 196, 248, 16, 83, 177, 198, 136, 77, 111, 134, 60, 219, 95, 246, 23, 5, 45, 14, 83, 29, 137, 248, 159, 28, 132, 142, 205, 99, 226, 213, 84, 232, 57, 130, 156, 81, 191, 237, 2, 65, 0, 255, 158, 212, 13, 43, 132, 244, 135, 148, 161, 232, 219, 20, 81, 196, 102, 103, 44, 110, 71, 100, 62, 73, 200, 32, 138, 114, 209, 171, 150, 179, 92, 198, 5, 190, 218, 79, 227, 227, 37, 32, 57, 159, 252, 107, 211, 139, 198, 202, 248, 137, 143, 186, 205, 106, 81, 85, 207, 134, 148, 110, 204, 243, 27, 2, 65, 0, 215, 4, 181, 121, 57, 224, 170, 168, 183, 159, 152, 8, 74, 233, 80, 244, 146, 81, 48, 159, 194, 199, 36, 187, 6, 181, 182, 223, 115, 133, 151, 171, 78, 219, 90, 161, 248, 69, 6, 207, 173, 3, 81, 161, 2, 60, 238, 204, 177, 12, 138, 17, 220, 179, 71, 113, 200, 248, 159, 153, 252, 150, 180, 155, 2, 65, 0, 190, 202, 185, 211, 170, 171, 238, 40, 84, 84, 21, 13, 144, 57, 7, 178, 183, 71, 126, 120, 98, 229, 235, 4, 40, 229, 173, 149, 185, 209, 29, 199, 29, 54, 164, 161, 38, 8, 30, 62, 83, 179, 47, 42, 165, 0, 156, 207, 160, 39, 169, 229, 81, 180, 136, 170, 116, 182, 20, 233, 45, 90, 100, 9, 2, 65, 0, 152, 255, 47, 198, 15, 201, 238, 133, 89, 11, 133, 153, 184, 252, 37, 239, 177, 65, 118, 80, 231, 190, 222, 66, 250, 118, 72, 166, 221, 67, 156, 245, 119, 138, 28, 6, 142, 107, 71, 122, 116, 200, 156, 199, 237, 152, 191, 239, 4, 184, 64, 114, 143, 81, 62, 48, 23, 233, 217, 95, 47, 221, 104, 171, 2, 64, 30, 219, 1, 230, 241, 70, 246, 243, 121, 174, 67, 66, 11, 99, 202, 17, 52, 234, 78, 29, 3, 57, 51, 123, 149, 86, 64, 192, 73, 199, 108, 101, 55, 232, 41, 114, 153, 237, 253, 52, 205, 148, 45, 86, 186, 241, 182, 183, 42, 77, 252, 195, 29, 158, 173, 3, 182, 207, 254, 61, 71, 184, 167, 184]); 4321 let keyPair = genKeyPairByData(pkData, skData); 4322 let inputUpdate: cryptoFramework.DataBlob = { data: new Uint8Array(buffer.from("This is Sign test plan1", 'utf-8').buffer) }; 4323 let inputSign: cryptoFramework.DataBlob = { data: new Uint8Array(buffer.from("This is Sign test plan2", 'utf-8').buffer) }; 4324 let signer = cryptoFramework.createSign('RSA1024|PKCS1|SHA256'); 4325 signer.initSync(keyPair.priKey); 4326 signer.updateSync(inputUpdate); 4327 let signData = signer.signSync(inputSign); 4328 console.info('signData result: ' + signData.data); 4329} 4330``` 4331 4332### setSignSpec<sup>10+</sup> 4333 4334setSignSpec(itemType: SignSpecItem, itemValue: number): void 4335 4336setSignSpec(itemType: SignSpecItem, itemValue: number \| Uint8Array): void 4337 4338Sets signing specifications. You can use this API to set signing parameters that cannot be set by [createSign](#cryptoframeworkcreatesign). 4339 4340Currently, only RSA and SM2 are supported. Since API version 11, SM2 signing parameters can be set. 4341 4342**Atomic service API**: This API can be used in atomic services since API version 12. 4343 4344**System capability**: SystemCapability.Security.CryptoFramework.Signature 4345 4346The supported system capability is SystemCapability.Security.CryptoFramework in API versions 10 to 11 and SystemCapability.Security.CryptoFramework.Signature since API version 12. 4347 4348**Parameters** 4349 4350| Name | Type | Mandatory| Description | 4351| -------- | -------------------- | ---- | ---------- | 4352| itemType | [SignSpecItem](#signspecitem10) | Yes | Signing parameter to set.| 4353| itemValue | number \| Uint8Array<sup>11+</sup> | Yes | Value of the signing parameter to set.| 4354 4355**Error codes** 4356For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 4357 4358| ID| Error Message | 4359| -------- | ---------------------- | 4360| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 4361| 801 | this operation is not supported. | 4362| 17620001 | memory error. | 4363| 17630001 | crypto operation error. | 4364 4365**Example** 4366 4367<!--code_no_check--> 4368```ts 4369let signer: cryptoFramework.Sign; // The process of generating the Sign instance is omitted here. 4370let setN = 20; 4371signer.setSignSpec(cryptoFramework.SignSpecItem.PSS_SALT_LEN_NUM, setN); 4372``` 4373 4374### getSignSpec<sup>10+</sup> 4375 4376getSignSpec(itemType: SignSpecItem): string | number 4377 4378Obtains signing specifications. Currently, only RSA is supported. 4379 4380**Atomic service API**: This API can be used in atomic services since API version 12. 4381 4382**System capability**: SystemCapability.Security.CryptoFramework.Signature 4383 4384The supported system capability is SystemCapability.Security.CryptoFramework in API versions 10 to 11 and SystemCapability.Security.CryptoFramework.Signature since API version 12. 4385 4386**Parameters** 4387 4388| Name| Type | Mandatory| Description | 4389| ------ | -------- | ---- | ---------- | 4390| itemType | [SignSpecItem](#signspecitem10) | Yes | Signing parameter to obtain.| 4391 4392**Return value** 4393 4394| Type | Description | 4395| -------------- | ----------- | 4396| string \| number | Returns the value of the signing parameter obtained.| 4397 4398**Error codes** 4399For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 4400 4401| ID| Error Message | 4402| -------- | ---------------------- | 4403| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 4404| 801 | this operation is not supported. | 4405| 17620001 | memory error. | 4406| 17630001 | crypto operation error. | 4407 4408**Example** 4409 4410<!--code_no_check--> 4411```ts 4412let signer: cryptoFramework.Sign; // The process of generating the Sign instance is omitted here. 4413let saltLen = signer.getSignSpec(cryptoFramework.SignSpecItem.PSS_SALT_LEN_NUM); 4414``` 4415 4416## cryptoFramework.createVerify 4417 4418createVerify(algName: string): Verify 4419 4420Creates a **Verify** instance. 4421 4422For details about the supported specifications, see [Signing and Signature Verification Overview and Algorithm Specifications](../../security/CryptoArchitectureKit/crypto-sign-sig-verify-overview.md). 4423 4424**Atomic service API**: This API can be used in atomic services since API version 12. 4425 4426**System capability**: SystemCapability.Security.CryptoFramework.Signature 4427 4428The supported system capability is SystemCapability.Security.CryptoFramework in API versions 9 to 11 and SystemCapability.Security.CryptoFramework.Signature since API version 12. 4429 4430**Parameters** 4431 4432| Name | Type | Mandatory| Description | 4433| ------- | ------ | ---- | ------------------------------------------------------------ | 4434| algName | string | Yes | Signing algorithm to use. Currently, RSA, ECC, DSA, SM2<sup>10+</sup> and Ed25519<sup>11+</sup> are supported. <br>If the RSA PKCS1 mode is used, you need to set the digest. If the RSA PSS mode is used, you need to set the digest and mask digest.<br>When the RSA algorithm is used for signature verification, you can use **Recover** to verify and recover the signed data.| 4435 4436**Return value** 4437 4438| Type | Description | 4439| ------ | ------------------------------------ | 4440| Verify | Returns the **Verify** instance created.| 4441 4442**Error codes** 4443For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 4444 4445| ID| Error Message | 4446| -------- | ---------------------- | 4447| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 4448| 801 | this operation is not supported. | 4449| 17620001 | memory error. | 4450 4451**Example** 4452 4453```ts 4454import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 4455 4456let verifyer1 = cryptoFramework.createVerify('RSA1024|PKCS1|SHA256'); 4457 4458let verifyer2 = cryptoFramework.createVerify('RSA1024|PSS|SHA256|MGF1_SHA256'); 4459 4460let verifyer3 = cryptoFramework.createVerify('RSA1024|PKCS1|SHA256|Recover'); 4461``` 4462 4463## Verify 4464 4465Provides APIs for signature verification. Before using any API of the **Verify** class, you must create a **Verify** instance by using [createVerify(algName: string): Verify](#cryptoframeworkcreateverify). Invoke **init()**, **update()**, and **sign()** in this class in sequence to complete the signature verification. For details about the sample code, see [Signing and Signature Verification with an RSA Key Pair (PKCS1 Mode)](../../security/CryptoArchitectureKit/crypto-rsa-sign-sig-verify-pkcs1.md). 4466 4467The **Verify** class does not support repeated initialization. When a new key is used for signature verification, you must create a new **Verify** instance and call **init()** for initialization. 4468 4469The signature verification mode is determined in **createVerify()**, and the key is set by **init()**. 4470 4471If 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()**. 4472 4473If 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. 4474 4475If the DSA algorithm is used for signature verification and the digest algorithm is **NoHash**, **update()** is not supported. If **update()** is called in this case, **ERR_CRYPTO_OPERATION** will be returned. 4476 4477### Attributes 4478 4479**Atomic service API**: This API can be used in atomic services since API version 12. 4480 4481**System capability**: SystemCapability.Security.CryptoFramework.Signature 4482 4483The supported system capability is SystemCapability.Security.CryptoFramework in API versions 9 to 11 and SystemCapability.Security.CryptoFramework.Signature since API version 12. 4484 4485| Name | Type | Readable| Writable| Description | 4486| ------- | ------ | ---- | ---- | ---------------------------- | 4487| algName | string | Yes | No | Algorithm to be used for signature verification.| 4488 4489### init 4490 4491init(pubKey: PubKey, callback: AsyncCallback\<void>): void 4492 4493Initializes the **Verify** instance with a public key. This API uses an asynchronous callback to return the result. **init**, **update**, and **verify** must be used together. **init** and **verify** are mandatory, and **update** is optional. 4494 4495**Atomic service API**: This API can be used in atomic services since API version 12. 4496 4497**System capability**: SystemCapability.Security.CryptoFramework.Signature 4498 4499The supported system capability is SystemCapability.Security.CryptoFramework in API versions 9 to 11 and SystemCapability.Security.CryptoFramework.Signature since API version 12. 4500 4501**Parameters** 4502 4503| Name | Type | Mandatory| Description | 4504| -------- | -------------------- | ---- | ------------------------------ | 4505| pubKey | [PubKey](#pubkey) | Yes | Public key used to initialize the **Verify** instance.| 4506| callback | AsyncCallback\<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object. | 4507 4508**Error codes** 4509For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 4510 4511| ID| Error Message | 4512| -------- | ---------------------- | 4513| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 4514| 17620001 | memory error. | 4515| 17620002 | runtime error. | 4516| 17630001 | crypto operation error. | 4517 4518### init 4519 4520init(pubKey: PubKey): Promise\<void> 4521 4522Initializes the **Verify** instance with a public key. This API uses a promise to return the result. **init**, **update**, and **verify** must be used together. **init** and **verify** are mandatory, and **update** is optional. 4523 4524**Atomic service API**: This API can be used in atomic services since API version 12. 4525 4526**System capability**: SystemCapability.Security.CryptoFramework.Signature 4527 4528The supported system capability is SystemCapability.Security.CryptoFramework in API versions 9 to 11 and SystemCapability.Security.CryptoFramework.Signature since API version 12. 4529 4530**Parameters** 4531 4532| Name| Type| Mandatory| Description | 4533| ------ | ---- | ---- | ---------------------------- | 4534| pubKey | [PubKey](#pubkey) | Yes | Public key used to initialize the **Verify** instance.| 4535 4536**Return value** 4537 4538| Type | Description | 4539| -------------- | ------------- | 4540| Promise\<void> | Promise that returns no value.| 4541 4542**Error codes** 4543For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 4544 4545| ID| Error Message | 4546| -------- | ---------------------- | 4547| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 4548| 17620001 | memory error. | 4549| 17620002 | runtime error. | 4550| 17630001 | crypto operation error. | 4551 4552### initSync<sup>12+</sup> 4553 4554initSync(pubKey: PubKey): void 4555 4556Initializes the **Verify** instance with a public key. This API returns the result synchronously. **initSync**, **updateSync**, and **verifySync** must be used together. **initSync** and **verifySync** are mandatory, and **updateSync** is optional. 4557 4558**Atomic service API**: This API can be used in atomic services since API version 12. 4559 4560**System capability**: SystemCapability.Security.CryptoFramework.Signature 4561 4562**Parameters** 4563 4564| Name| Type| Mandatory| Description | 4565| ------ | ---- | ---- | ---------------------------- | 4566| pubKey | [PubKey](#pubkey) | Yes | Public key used to initialize the **Verify** instance.| 4567 4568**Return value** 4569 4570| Type | Description | 4571| -------------- | ------------- | 4572| void | No value is returned.| 4573 4574**Error codes** 4575For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 4576 4577| ID| Error Message | 4578| -------- | ---------------------- | 4579| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 4580| 17620001 | memory error. | 4581| 17620002 | runtime error. | 4582| 17630001 | crypto operation error. | 4583 4584### update 4585 4586update(data: DataBlob, callback: AsyncCallback\<void>): void 4587 4588Updates the data for signature verification. This API uses an asynchronous callback to return the result. 4589 4590This API can be called only after the [Verify](#verify) instance is initialized using [init()](#init-4). 4591 4592> **NOTE** 4593> 4594> You can call **update** multiple times or do not use **update** (call [verify](#verify-1) after [init](#init-4)), depending on the data volume.<br> 4595> The amount of the data to be passed in by **update()** (one-time or accumulative) is not limited. If there is a large amount of data, you are advised to call **update()** multiple times to pass in the data by segment. This prevents too much memory from being requested at a time.<br> 4596> For details about the sample code for calling **update()** multiple times in signature verification, see [Signing and Signature Verification by Segment with an RSA Key Pair (PKCS1 Mode)](../../security/CryptoArchitectureKit/crypto-rsa-sign-sig-verify-pkcs1-by-segment.md). The operations of other algorithms are similar.<br> 4597> If the DSA algorithm is used for signature verification and the digest algorithm is **NoHash**, **update()** is not supported. If **update()** is called in this case, **ERR_CRYPTO_OPERATION** will be returned. 4598 4599**Atomic service API**: This API can be used in atomic services since API version 12. 4600 4601**System capability**: SystemCapability.Security.CryptoFramework.Signature 4602 4603The supported system capability is SystemCapability.Security.CryptoFramework in API versions 9 to 11 and SystemCapability.Security.CryptoFramework.Signature since API version 12. 4604 4605**Parameters** 4606 4607| Name | Type | Mandatory| Description | 4608| -------- | --------------------- | ---- | ------------ | 4609| data | [DataBlob](#datablob) | Yes | Data to pass in.| 4610| callback | AsyncCallback\<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.| 4611 4612**Error codes** 4613For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 4614 4615| ID| Error Message | 4616| -------- | ---------------------- | 4617| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 4618| 17620001 | memory error. | 4619| 17620002 | runtime error. | 4620| 17630001 | crypto operation error. | 4621 4622### update 4623 4624update(data: DataBlob): Promise\<void> 4625 4626Updates the data for signature verifications. This API uses a promise to return the result. 4627 4628This API can be called only after the [Verify](#verify) instance is initialized using [init()](#init-5). 4629 4630> **NOTE** 4631> 4632> You can call **update** multiple times or do not use **update** (call [verify](#verify-2) after [init](#init-5)), depending on the data volume.<br> 4633> The amount of the data to be passed in by **update()** (one-time or accumulative) is not limited. If there is a large amount of data, you are advised to call **update()** multiple times to pass in the data by segment. This prevents too much memory from being requested at a time.<br> 4634> For details about the sample code for calling **update()** multiple times in signature verification, see [Signing and Signature Verification by Segment with an RSA Key Pair (PKCS1 Mode)](../../security/CryptoArchitectureKit/crypto-rsa-sign-sig-verify-pkcs1-by-segment.md). The operations of other algorithms are similar.<br> 4635> If the DSA algorithm is used for signature verification and the digest algorithm is **NoHash**, **update()** is not supported. If **update()** is called in this case, **ERR_CRYPTO_OPERATION** will be returned. 4636 4637**Atomic service API**: This API can be used in atomic services since API version 12. 4638 4639**System capability**: SystemCapability.Security.CryptoFramework.Signature 4640 4641The supported system capability is SystemCapability.Security.CryptoFramework in API versions 9 to 11 and SystemCapability.Security.CryptoFramework.Signature since API version 12. 4642 4643**Parameters** 4644 4645| Name| Type | Mandatory| Description | 4646| ------ | -------- | ---- | ---------- | 4647| data | [DataBlob](#datablob) | Yes | Data to pass in.| 4648 4649**Return value** 4650 4651| Type | Description | 4652| -------------- | ------------- | 4653| Promise\<void> | Promise that returns no value.| 4654 4655**Error codes** 4656For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 4657 4658| ID| Error Message | 4659| -------- | ---------------------- | 4660| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 4661| 17620001 | memory error. | 4662| 17620002 | runtime error. | 4663| 17630001 | crypto operation error. | 4664 4665### updateSync<sup>12+</sup> 4666 4667updateSync(data: DataBlob): void 4668 4669Updates the data for signature verifications. This API returns the result synchronously. 4670 4671This API can be called only after the [Verify](#verify) instance is initialized by using [initSync()](#initsync12-2). 4672 4673> **NOTE** 4674> 4675> You can call **updateSync** multiple times or do not use **updateSync** (call [verifySync](#verifysync12)after [initSync](#initsync12-2)), depending on the data volume.<br> 4676> The amount of the data to be passed in by **updateSync** (one-time or accumulative) is not limited. If there is a large amount of data, you are advised to call **updateSync** multiple times to pass in the data by segment. This prevents too much memory from being requested at a time.<br> 4677> For details about the sample code for calling **updateSync** multiple times in signature verification, see [Signing and Signature Verification by Segment with an RSA Key Pair (PKCS1 Mode)](../../security/CryptoArchitectureKit/crypto-rsa-sign-sig-verify-pkcs1-by-segment.md). The operations of other algorithms are similar.<br> 4678> If the DSA algorithm is used for signature verification and the digest algorithm is **NoHash**, **updateSync** is not supported. If **updateSync** is called in this case, **ERR_CRYPTO_OPERATION** will be returned. 4679 4680**Atomic service API**: This API can be used in atomic services since API version 12. 4681 4682**System capability**: SystemCapability.Security.CryptoFramework.Signature 4683 4684**Parameters** 4685 4686| Name| Type | Mandatory| Description | 4687| ------ | -------- | ---- | ---------- | 4688| data | [DataBlob](#datablob) | Yes | Data to pass in.| 4689 4690**Return value** 4691 4692| Type | Description | 4693| -------------- | ------------- | 4694| void | No value is returned.| 4695 4696**Error codes** 4697For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 4698 4699| ID| Error Message | 4700| -------- | ---------------------- | 4701| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 4702| 17620001 | memory error. | 4703| 17620002 | runtime error. | 4704| 17630001 | crypto operation error. | 4705 4706### verify 4707 4708verify(data: DataBlob | null, signatureData: DataBlob, callback: AsyncCallback\<boolean>): void 4709 4710Verifies the signature. This API uses an asynchronous callback to return the result. 4711 4712**Atomic service API**: This API can be used in atomic services since API version 12. 4713 4714**System capability**: SystemCapability.Security.CryptoFramework.Signature 4715 4716The supported system capability is SystemCapability.Security.CryptoFramework in API versions 9 to 11 and SystemCapability.Security.CryptoFramework.Signature since API version 12. 4717 4718**Parameters** 4719 4720| Name | Type | Mandatory| Description | 4721| ------------- | -------------------- | ---- | ---------- | 4722| 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.| 4723| signatureData | [DataBlob](#datablob) | Yes | Signature data. | 4724| callback | AsyncCallback\<boolean> | Yes | Callback invoked to return the signature verification result.| 4725 4726**Error codes** 4727For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 4728 4729| ID| Error Message | 4730| -------- | ---------------------- | 4731| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 4732| 17620001 | memory error. | 4733| 17620002 | runtime error. | 4734| 17630001 | crypto operation error. | 4735 4736### verify 4737 4738verify(data: DataBlob | null, signatureData: DataBlob): Promise\<boolean> 4739 4740Verifies the signature. This API uses a promise to return the result. 4741 4742**Atomic service API**: This API can be used in atomic services since API version 12. 4743 4744**System capability**: SystemCapability.Security.CryptoFramework.Signature 4745 4746The supported system capability is SystemCapability.Security.CryptoFramework in API versions 9 to 11 and SystemCapability.Security.CryptoFramework.Signature since API version 12. 4747 4748**Parameters** 4749 4750| Name | Type | Mandatory| Description | 4751| ------------- | -------- | ---- | ---------- | 4752| 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.| 4753| signatureData | [DataBlob](#datablob) | Yes | Signature data. | 4754 4755**Return value** 4756 4757| Type | Description | 4758| ----------------- | ------------------------------ | 4759| Promise\<boolean> | Promise used to return the result.| 4760 4761**Error codes** 4762For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 4763 4764| ID| Error Message | 4765| -------- | ---------------------- | 4766| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 4767| 17620001 | memory error. | 4768| 17620002 | runtime error. | 4769| 17630001 | crypto operation error. | 4770 4771### verifySync<sup>12+</sup> 4772 4773verifySync(data: DataBlob | null, signatureData: DataBlob): boolean 4774 4775Verifies the signature. This API returns the verification result synchronously. 4776 4777**Atomic service API**: This API can be used in atomic services since API version 12. 4778 4779**System capability**: SystemCapability.Security.CryptoFramework.Signature 4780 4781**Parameters** 4782 4783| Name | Type | Mandatory| Description | 4784| ------------- | -------- | ---- | ---------- | 4785| data | [DataBlob](#datablob) \| null | Yes | Data to pass in.| 4786| signatureData | [DataBlob](#datablob) | Yes | Signature data. | 4787 4788**Return value** 4789 4790| Type | Description | 4791| ----------------- | ------------------------------ | 4792| boolean | Signature verification result.| 4793 4794**Error codes** 4795For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 4796 4797| ID| Error Message | 4798| -------- | ---------------------- | 4799| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 4800| 17620001 | memory error. | 4801| 17620002 | runtime error. | 4802| 17630001 | crypto operation error. | 4803 4804**Example (using the callback-based API)** 4805 4806For more examples of signing and signature verification, see [Signing and Signature Verification with an RSA Key Pair (PKCS1 Mode)](../../security/CryptoArchitectureKit/crypto-rsa-sign-sig-verify-pkcs1.md). 4807 4808```ts 4809import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 4810import { buffer } from '@kit.ArkTS'; 4811 4812function verifyByCallback() { 4813 let inputUpdate: cryptoFramework.DataBlob = { data: new Uint8Array(buffer.from("This is Sign test plan1", 'utf-8').buffer) }; 4814 let inputVerify: cryptoFramework.DataBlob = { data: new Uint8Array(buffer.from("This is Sign test plan2", 'utf-8').buffer) }; 4815 // Key generated based on the key data and input data for signature verification. If the data in verify() is the same as that in sign(), the signature verification is successful. 4816 let pkData = new Uint8Array([48, 129, 159, 48, 13, 6, 9, 42, 134, 72, 134, 247, 13, 1, 1, 1, 5, 0, 3, 129, 141, 0, 48, 129, 137, 2, 129, 129, 0, 214, 179, 23, 198, 183, 139, 148, 8, 173, 74, 56, 160, 15, 248, 244, 166, 209, 250, 142, 74, 216, 58, 117, 215, 178, 247, 254, 39, 180, 227, 85, 201, 59, 133, 209, 221, 26, 9, 116, 31, 172, 151, 252, 185, 123, 20, 25, 7, 92, 129, 5, 196, 239, 214, 126, 254, 154, 188, 239, 144, 161, 171, 65, 42, 31, 214, 93, 115, 247, 69, 94, 143, 54, 51, 25, 49, 146, 204, 205, 165, 20, 120, 35, 184, 190, 65, 106, 12, 214, 176, 57, 125, 235, 51, 88, 135, 76, 73, 109, 112, 147, 138, 198, 252, 5, 20, 245, 51, 7, 32, 108, 89, 125, 204, 50, 189, 88, 254, 255, 146, 244, 244, 149, 79, 54, 216, 45, 89, 2, 3, 1, 0, 1]); 4817 let skData = new Uint8Array([48, 130, 2, 120, 2, 1, 0, 48, 13, 6, 9, 42, 134, 72, 134, 247, 13, 1, 1, 1, 5, 0, 4, 130, 2, 98, 48, 130, 2, 94, 2, 1, 0, 2, 129, 129, 0, 214, 179, 23, 198, 183, 139, 148, 8, 173, 74, 56, 160, 15, 248, 244, 166, 209, 250, 142, 74, 216, 58, 117, 215, 178, 247, 254, 39, 180, 227, 85, 201, 59, 133, 209, 221, 26, 9, 116, 31, 172, 151, 252, 185, 123, 20, 25, 7, 92, 129, 5, 196, 239, 214, 126, 254, 154, 188, 239, 144, 161, 171, 65, 42, 31, 214, 93, 115, 247, 69, 94, 143, 54, 51, 25, 49, 146, 204, 205, 165, 20, 120, 35, 184, 190, 65, 106, 12, 214, 176, 57, 125, 235, 51, 88, 135, 76, 73, 109, 112, 147, 138, 198, 252, 5, 20, 245, 51, 7, 32, 108, 89, 125, 204, 50, 189, 88, 254, 255, 146, 244, 244, 149, 79, 54, 216, 45, 89, 2, 3, 1, 0, 1, 2, 129, 129, 0, 152, 111, 145, 203, 10, 88, 116, 163, 112, 126, 9, 20, 68, 34, 235, 121, 98, 14, 182, 102, 151, 125, 114, 91, 210, 122, 215, 29, 212, 5, 176, 203, 238, 146, 5, 190, 41, 21, 91, 56, 125, 239, 111, 133, 53, 200, 192, 56, 132, 202, 42, 145, 120, 3, 224, 40, 223, 46, 148, 29, 41, 92, 17, 40, 12, 72, 165, 69, 192, 211, 142, 233, 81, 202, 177, 235, 156, 27, 179, 48, 18, 85, 154, 101, 193, 45, 218, 91, 24, 143, 196, 248, 16, 83, 177, 198, 136, 77, 111, 134, 60, 219, 95, 246, 23, 5, 45, 14, 83, 29, 137, 248, 159, 28, 132, 142, 205, 99, 226, 213, 84, 232, 57, 130, 156, 81, 191, 237, 2, 65, 0, 255, 158, 212, 13, 43, 132, 244, 135, 148, 161, 232, 219, 20, 81, 196, 102, 103, 44, 110, 71, 100, 62, 73, 200, 32, 138, 114, 209, 171, 150, 179, 92, 198, 5, 190, 218, 79, 227, 227, 37, 32, 57, 159, 252, 107, 211, 139, 198, 202, 248, 137, 143, 186, 205, 106, 81, 85, 207, 134, 148, 110, 204, 243, 27, 2, 65, 0, 215, 4, 181, 121, 57, 224, 170, 168, 183, 159, 152, 8, 74, 233, 80, 244, 146, 81, 48, 159, 194, 199, 36, 187, 6, 181, 182, 223, 115, 133, 151, 171, 78, 219, 90, 161, 248, 69, 6, 207, 173, 3, 81, 161, 2, 60, 238, 204, 177, 12, 138, 17, 220, 179, 71, 113, 200, 248, 159, 153, 252, 150, 180, 155, 2, 65, 0, 190, 202, 185, 211, 170, 171, 238, 40, 84, 84, 21, 13, 144, 57, 7, 178, 183, 71, 126, 120, 98, 229, 235, 4, 40, 229, 173, 149, 185, 209, 29, 199, 29, 54, 164, 161, 38, 8, 30, 62, 83, 179, 47, 42, 165, 0, 156, 207, 160, 39, 169, 229, 81, 180, 136, 170, 116, 182, 20, 233, 45, 90, 100, 9, 2, 65, 0, 152, 255, 47, 198, 15, 201, 238, 133, 89, 11, 133, 153, 184, 252, 37, 239, 177, 65, 118, 80, 231, 190, 222, 66, 250, 118, 72, 166, 221, 67, 156, 245, 119, 138, 28, 6, 142, 107, 71, 122, 116, 200, 156, 199, 237, 152, 191, 239, 4, 184, 64, 114, 143, 81, 62, 48, 23, 233, 217, 95, 47, 221, 104, 171, 2, 64, 30, 219, 1, 230, 241, 70, 246, 243, 121, 174, 67, 66, 11, 99, 202, 17, 52, 234, 78, 29, 3, 57, 51, 123, 149, 86, 64, 192, 73, 199, 108, 101, 55, 232, 41, 114, 153, 237, 253, 52, 205, 148, 45, 86, 186, 241, 182, 183, 42, 77, 252, 195, 29, 158, 173, 3, 182, 207, 254, 61, 71, 184, 167, 184]); 4818 let pubKeyBlob: cryptoFramework.DataBlob = { data: pkData }; 4819 let priKeyBlob: cryptoFramework.DataBlob = { data: skData }; 4820 // The data is signData.data in Sign(). 4821 let signMessageBlob: cryptoFramework.DataBlob = { data: new Uint8Array([9, 68, 164, 161, 230, 155, 255, 153, 10, 12, 14, 22, 146, 115, 209, 167, 223, 133, 89, 173, 50, 249, 176, 104, 10, 251, 219, 104, 117, 196, 105, 65, 249, 139, 119, 41, 15, 171, 191, 11, 177, 177, 1, 119, 130, 142, 87, 183, 32, 220, 226, 28, 38, 73, 222, 172, 153, 26, 87, 58, 188, 42, 150, 67, 94, 214, 147, 64, 202, 87, 155, 125, 254, 112, 95, 176, 255, 207, 106, 43, 228, 153, 131, 240, 120, 88, 253, 179, 207, 207, 110, 223, 173, 15, 113, 11, 183, 122, 237, 205, 206, 123, 246, 33, 167, 169, 251, 237, 199, 26, 220, 152, 190, 117, 131, 74, 232, 50, 39, 172, 232, 178, 112, 73, 251, 235, 131, 209]) } 4822 let rsaGenerator = cryptoFramework.createAsyKeyGenerator('RSA1024'); 4823 let verifyer = cryptoFramework.createVerify('RSA1024|PKCS1|SHA256'); 4824 rsaGenerator.convertKey(pubKeyBlob, priKeyBlob, (err, keyPair) => { 4825 verifyer.init(keyPair.pubKey, err => { 4826 verifyer.update(inputUpdate, err => { 4827 verifyer.verify(inputVerify, signMessageBlob, (err, res) => { 4828 console.info('verify result is ' + res); 4829 }); 4830 }); 4831 }); 4832 }); 4833} 4834``` 4835 4836**Example (using the promise-based API)** 4837 4838For more examples of signing and signature verification, see [Signing and Signature Verification with an RSA Key Pair (PKCS1 Mode)](../../security/CryptoArchitectureKit/crypto-rsa-sign-sig-verify-pkcs1.md). 4839 4840```ts 4841import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 4842import { buffer } from '@kit.ArkTS'; 4843 4844async function genKeyPairByData(pubKeyData: Uint8Array, priKeyData: Uint8Array) { 4845 let pubKeyBlob: cryptoFramework.DataBlob = { data: pubKeyData }; 4846 let priKeyBlob: cryptoFramework.DataBlob = { data: priKeyData }; 4847 let rsaGenerator = cryptoFramework.createAsyKeyGenerator('RSA1024'); 4848 let keyPair = await rsaGenerator.convertKey(pubKeyBlob, priKeyBlob); 4849 console.info('convertKey success'); 4850 return keyPair; 4851} 4852 4853async function verifyByPromise() { 4854 // Key generated based on the key data and input data for signature verification. If the data in verify() is the same as that in sign(), the signature verification is successful. 4855 let pkData = new Uint8Array([48, 129, 159, 48, 13, 6, 9, 42, 134, 72, 134, 247, 13, 1, 1, 1, 5, 0, 3, 129, 141, 0, 48, 129, 137, 2, 129, 129, 0, 214, 179, 23, 198, 183, 139, 148, 8, 173, 74, 56, 160, 15, 248, 244, 166, 209, 250, 142, 74, 216, 58, 117, 215, 178, 247, 254, 39, 180, 227, 85, 201, 59, 133, 209, 221, 26, 9, 116, 31, 172, 151, 252, 185, 123, 20, 25, 7, 92, 129, 5, 196, 239, 214, 126, 254, 154, 188, 239, 144, 161, 171, 65, 42, 31, 214, 93, 115, 247, 69, 94, 143, 54, 51, 25, 49, 146, 204, 205, 165, 20, 120, 35, 184, 190, 65, 106, 12, 214, 176, 57, 125, 235, 51, 88, 135, 76, 73, 109, 112, 147, 138, 198, 252, 5, 20, 245, 51, 7, 32, 108, 89, 125, 204, 50, 189, 88, 254, 255, 146, 244, 244, 149, 79, 54, 216, 45, 89, 2, 3, 1, 0, 1]); 4856 let skData = new Uint8Array([48, 130, 2, 120, 2, 1, 0, 48, 13, 6, 9, 42, 134, 72, 134, 247, 13, 1, 1, 1, 5, 0, 4, 130, 2, 98, 48, 130, 2, 94, 2, 1, 0, 2, 129, 129, 0, 214, 179, 23, 198, 183, 139, 148, 8, 173, 74, 56, 160, 15, 248, 244, 166, 209, 250, 142, 74, 216, 58, 117, 215, 178, 247, 254, 39, 180, 227, 85, 201, 59, 133, 209, 221, 26, 9, 116, 31, 172, 151, 252, 185, 123, 20, 25, 7, 92, 129, 5, 196, 239, 214, 126, 254, 154, 188, 239, 144, 161, 171, 65, 42, 31, 214, 93, 115, 247, 69, 94, 143, 54, 51, 25, 49, 146, 204, 205, 165, 20, 120, 35, 184, 190, 65, 106, 12, 214, 176, 57, 125, 235, 51, 88, 135, 76, 73, 109, 112, 147, 138, 198, 252, 5, 20, 245, 51, 7, 32, 108, 89, 125, 204, 50, 189, 88, 254, 255, 146, 244, 244, 149, 79, 54, 216, 45, 89, 2, 3, 1, 0, 1, 2, 129, 129, 0, 152, 111, 145, 203, 10, 88, 116, 163, 112, 126, 9, 20, 68, 34, 235, 121, 98, 14, 182, 102, 151, 125, 114, 91, 210, 122, 215, 29, 212, 5, 176, 203, 238, 146, 5, 190, 41, 21, 91, 56, 125, 239, 111, 133, 53, 200, 192, 56, 132, 202, 42, 145, 120, 3, 224, 40, 223, 46, 148, 29, 41, 92, 17, 40, 12, 72, 165, 69, 192, 211, 142, 233, 81, 202, 177, 235, 156, 27, 179, 48, 18, 85, 154, 101, 193, 45, 218, 91, 24, 143, 196, 248, 16, 83, 177, 198, 136, 77, 111, 134, 60, 219, 95, 246, 23, 5, 45, 14, 83, 29, 137, 248, 159, 28, 132, 142, 205, 99, 226, 213, 84, 232, 57, 130, 156, 81, 191, 237, 2, 65, 0, 255, 158, 212, 13, 43, 132, 244, 135, 148, 161, 232, 219, 20, 81, 196, 102, 103, 44, 110, 71, 100, 62, 73, 200, 32, 138, 114, 209, 171, 150, 179, 92, 198, 5, 190, 218, 79, 227, 227, 37, 32, 57, 159, 252, 107, 211, 139, 198, 202, 248, 137, 143, 186, 205, 106, 81, 85, 207, 134, 148, 110, 204, 243, 27, 2, 65, 0, 215, 4, 181, 121, 57, 224, 170, 168, 183, 159, 152, 8, 74, 233, 80, 244, 146, 81, 48, 159, 194, 199, 36, 187, 6, 181, 182, 223, 115, 133, 151, 171, 78, 219, 90, 161, 248, 69, 6, 207, 173, 3, 81, 161, 2, 60, 238, 204, 177, 12, 138, 17, 220, 179, 71, 113, 200, 248, 159, 153, 252, 150, 180, 155, 2, 65, 0, 190, 202, 185, 211, 170, 171, 238, 40, 84, 84, 21, 13, 144, 57, 7, 178, 183, 71, 126, 120, 98, 229, 235, 4, 40, 229, 173, 149, 185, 209, 29, 199, 29, 54, 164, 161, 38, 8, 30, 62, 83, 179, 47, 42, 165, 0, 156, 207, 160, 39, 169, 229, 81, 180, 136, 170, 116, 182, 20, 233, 45, 90, 100, 9, 2, 65, 0, 152, 255, 47, 198, 15, 201, 238, 133, 89, 11, 133, 153, 184, 252, 37, 239, 177, 65, 118, 80, 231, 190, 222, 66, 250, 118, 72, 166, 221, 67, 156, 245, 119, 138, 28, 6, 142, 107, 71, 122, 116, 200, 156, 199, 237, 152, 191, 239, 4, 184, 64, 114, 143, 81, 62, 48, 23, 233, 217, 95, 47, 221, 104, 171, 2, 64, 30, 219, 1, 230, 241, 70, 246, 243, 121, 174, 67, 66, 11, 99, 202, 17, 52, 234, 78, 29, 3, 57, 51, 123, 149, 86, 64, 192, 73, 199, 108, 101, 55, 232, 41, 114, 153, 237, 253, 52, 205, 148, 45, 86, 186, 241, 182, 183, 42, 77, 252, 195, 29, 158, 173, 3, 182, 207, 254, 61, 71, 184, 167, 184]); 4857 let keyPair = await genKeyPairByData(pkData, skData); 4858 let inputUpdate: cryptoFramework.DataBlob = { data: new Uint8Array(buffer.from("This is Sign test plan1", 'utf-8').buffer) }; 4859 let inputVerify: cryptoFramework.DataBlob = { data: new Uint8Array(buffer.from("This is Sign test plan2", 'utf-8').buffer) }; 4860 // The data is signData.data in Sign(). 4861 let signMessageBlob: cryptoFramework.DataBlob = { data: new Uint8Array([9, 68, 164, 161, 230, 155, 255, 153, 10, 12, 14, 22, 146, 115, 209, 167, 223, 133, 89, 173, 50, 249, 176, 104, 10, 251, 219, 104, 117, 196, 105, 65, 249, 139, 119, 41, 15, 171, 191, 11, 177, 177, 1, 119, 130, 142, 87, 183, 32, 220, 226, 28, 38, 73, 222, 172, 153, 26, 87, 58, 188, 42, 150, 67, 94, 214, 147, 64, 202, 87, 155, 125, 254, 112, 95, 176, 255, 207, 106, 43, 228, 153, 131, 240, 120, 88, 253, 179, 207, 207, 110, 223, 173, 15, 113, 11, 183, 122, 237, 205, 206, 123, 246, 33, 167, 169, 251, 237, 199, 26, 220, 152, 190, 117, 131, 74, 232, 50, 39, 172, 232, 178, 112, 73, 251, 235, 131, 209]) }; 4862 let verifier = cryptoFramework.createVerify('RSA1024|PKCS1|SHA256'); 4863 await verifier.init(keyPair.pubKey); 4864 await verifier.update(inputUpdate); 4865 let res = await verifier.verify(inputVerify, signMessageBlob); 4866 console.info('verify result: ' + res); 4867} 4868``` 4869 4870**Example (using the sync API)** 4871 4872For more examples of signing and signature verification, see [Signing and Signature Verification with an RSA Key Pair (PKCS1 Mode)](../../security/CryptoArchitectureKit/crypto-rsa-sign-sig-verify-pkcs1.md). 4873 4874```ts 4875import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 4876import { buffer } from '@kit.ArkTS'; 4877 4878function genKeyPairByData(pubKeyData: Uint8Array, priKeyData: Uint8Array) { 4879 let pubKeyBlob: cryptoFramework.DataBlob = { data: pubKeyData }; 4880 let priKeyBlob: cryptoFramework.DataBlob = { data: priKeyData }; 4881 let rsaGenerator = cryptoFramework.createAsyKeyGenerator('RSA1024'); 4882 let keyPair = rsaGenerator.convertKeySync(pubKeyBlob, priKeyBlob); 4883 console.info('convertKey success'); 4884 return keyPair; 4885} 4886 4887function verifyBySync() { 4888 // Key generated based on the key data and input data for signature verification. If the data in verify() is the same as that in sign(), the signature verification is successful. 4889 let pkData = new Uint8Array([48, 129, 159, 48, 13, 6, 9, 42, 134, 72, 134, 247, 13, 1, 1, 1, 5, 0, 3, 129, 141, 0, 48, 129, 137, 2, 129, 129, 0, 214, 179, 23, 198, 183, 139, 148, 8, 173, 74, 56, 160, 15, 248, 244, 166, 209, 250, 142, 74, 216, 58, 117, 215, 178, 247, 254, 39, 180, 227, 85, 201, 59, 133, 209, 221, 26, 9, 116, 31, 172, 151, 252, 185, 123, 20, 25, 7, 92, 129, 5, 196, 239, 214, 126, 254, 154, 188, 239, 144, 161, 171, 65, 42, 31, 214, 93, 115, 247, 69, 94, 143, 54, 51, 25, 49, 146, 204, 205, 165, 20, 120, 35, 184, 190, 65, 106, 12, 214, 176, 57, 125, 235, 51, 88, 135, 76, 73, 109, 112, 147, 138, 198, 252, 5, 20, 245, 51, 7, 32, 108, 89, 125, 204, 50, 189, 88, 254, 255, 146, 244, 244, 149, 79, 54, 216, 45, 89, 2, 3, 1, 0, 1]); 4890 let skData = new Uint8Array([48, 130, 2, 120, 2, 1, 0, 48, 13, 6, 9, 42, 134, 72, 134, 247, 13, 1, 1, 1, 5, 0, 4, 130, 2, 98, 48, 130, 2, 94, 2, 1, 0, 2, 129, 129, 0, 214, 179, 23, 198, 183, 139, 148, 8, 173, 74, 56, 160, 15, 248, 244, 166, 209, 250, 142, 74, 216, 58, 117, 215, 178, 247, 254, 39, 180, 227, 85, 201, 59, 133, 209, 221, 26, 9, 116, 31, 172, 151, 252, 185, 123, 20, 25, 7, 92, 129, 5, 196, 239, 214, 126, 254, 154, 188, 239, 144, 161, 171, 65, 42, 31, 214, 93, 115, 247, 69, 94, 143, 54, 51, 25, 49, 146, 204, 205, 165, 20, 120, 35, 184, 190, 65, 106, 12, 214, 176, 57, 125, 235, 51, 88, 135, 76, 73, 109, 112, 147, 138, 198, 252, 5, 20, 245, 51, 7, 32, 108, 89, 125, 204, 50, 189, 88, 254, 255, 146, 244, 244, 149, 79, 54, 216, 45, 89, 2, 3, 1, 0, 1, 2, 129, 129, 0, 152, 111, 145, 203, 10, 88, 116, 163, 112, 126, 9, 20, 68, 34, 235, 121, 98, 14, 182, 102, 151, 125, 114, 91, 210, 122, 215, 29, 212, 5, 176, 203, 238, 146, 5, 190, 41, 21, 91, 56, 125, 239, 111, 133, 53, 200, 192, 56, 132, 202, 42, 145, 120, 3, 224, 40, 223, 46, 148, 29, 41, 92, 17, 40, 12, 72, 165, 69, 192, 211, 142, 233, 81, 202, 177, 235, 156, 27, 179, 48, 18, 85, 154, 101, 193, 45, 218, 91, 24, 143, 196, 248, 16, 83, 177, 198, 136, 77, 111, 134, 60, 219, 95, 246, 23, 5, 45, 14, 83, 29, 137, 248, 159, 28, 132, 142, 205, 99, 226, 213, 84, 232, 57, 130, 156, 81, 191, 237, 2, 65, 0, 255, 158, 212, 13, 43, 132, 244, 135, 148, 161, 232, 219, 20, 81, 196, 102, 103, 44, 110, 71, 100, 62, 73, 200, 32, 138, 114, 209, 171, 150, 179, 92, 198, 5, 190, 218, 79, 227, 227, 37, 32, 57, 159, 252, 107, 211, 139, 198, 202, 248, 137, 143, 186, 205, 106, 81, 85, 207, 134, 148, 110, 204, 243, 27, 2, 65, 0, 215, 4, 181, 121, 57, 224, 170, 168, 183, 159, 152, 8, 74, 233, 80, 244, 146, 81, 48, 159, 194, 199, 36, 187, 6, 181, 182, 223, 115, 133, 151, 171, 78, 219, 90, 161, 248, 69, 6, 207, 173, 3, 81, 161, 2, 60, 238, 204, 177, 12, 138, 17, 220, 179, 71, 113, 200, 248, 159, 153, 252, 150, 180, 155, 2, 65, 0, 190, 202, 185, 211, 170, 171, 238, 40, 84, 84, 21, 13, 144, 57, 7, 178, 183, 71, 126, 120, 98, 229, 235, 4, 40, 229, 173, 149, 185, 209, 29, 199, 29, 54, 164, 161, 38, 8, 30, 62, 83, 179, 47, 42, 165, 0, 156, 207, 160, 39, 169, 229, 81, 180, 136, 170, 116, 182, 20, 233, 45, 90, 100, 9, 2, 65, 0, 152, 255, 47, 198, 15, 201, 238, 133, 89, 11, 133, 153, 184, 252, 37, 239, 177, 65, 118, 80, 231, 190, 222, 66, 250, 118, 72, 166, 221, 67, 156, 245, 119, 138, 28, 6, 142, 107, 71, 122, 116, 200, 156, 199, 237, 152, 191, 239, 4, 184, 64, 114, 143, 81, 62, 48, 23, 233, 217, 95, 47, 221, 104, 171, 2, 64, 30, 219, 1, 230, 241, 70, 246, 243, 121, 174, 67, 66, 11, 99, 202, 17, 52, 234, 78, 29, 3, 57, 51, 123, 149, 86, 64, 192, 73, 199, 108, 101, 55, 232, 41, 114, 153, 237, 253, 52, 205, 148, 45, 86, 186, 241, 182, 183, 42, 77, 252, 195, 29, 158, 173, 3, 182, 207, 254, 61, 71, 184, 167, 184]); 4891 let keyPair = genKeyPairByData(pkData, skData); 4892 let inputUpdate: cryptoFramework.DataBlob = { data: new Uint8Array(buffer.from("This is Sign test plan1", 'utf-8').buffer) }; 4893 let inputVerify: cryptoFramework.DataBlob = { data: new Uint8Array(buffer.from("This is Sign test plan2", 'utf-8').buffer) }; 4894 // The data is signData.data in Sign(). 4895 let signMessageBlob: cryptoFramework.DataBlob = { data: new Uint8Array([9, 68, 164, 161, 230, 155, 255, 153, 10, 12, 14, 22, 146, 115, 209, 167, 223, 133, 89, 173, 50, 249, 176, 104, 10, 251, 219, 104, 117, 196, 105, 65, 249, 139, 119, 41, 15, 171, 191, 11, 177, 177, 1, 119, 130, 142, 87, 183, 32, 220, 226, 28, 38, 73, 222, 172, 153, 26, 87, 58, 188, 42, 150, 67, 94, 214, 147, 64, 202, 87, 155, 125, 254, 112, 95, 176, 255, 207, 106, 43, 228, 153, 131, 240, 120, 88, 253, 179, 207, 207, 110, 223, 173, 15, 113, 11, 183, 122, 237, 205, 206, 123, 246, 33, 167, 169, 251, 237, 199, 26, 220, 152, 190, 117, 131, 74, 232, 50, 39, 172, 232, 178, 112, 73, 251, 235, 131, 209]) }; 4896 let verifier = cryptoFramework.createVerify('RSA1024|PKCS1|SHA256'); 4897 verifier.initSync(keyPair.pubKey); 4898 verifier.updateSync(inputUpdate); 4899 let res = verifier.verifySync(inputVerify, signMessageBlob); 4900 console.info('verify result: ' + res); 4901} 4902``` 4903 4904### recover<sup>12+</sup> 4905 4906recover(signatureData: DataBlob): Promise\<DataBlob | null> 4907 4908Recovers the original data from a signature. This API uses a promise to return the result. 4909 4910> **NOTE** 4911> 4912> Currently, only RSA is supported. 4913 4914**Atomic service API**: This API can be used in atomic services since API version 12. 4915 4916**System capability**: SystemCapability.Security.CryptoFramework.Signature 4917 4918**Parameters** 4919 4920| Name | Type | Mandatory| Description | 4921| ------------- | -------- | ---- | ---------- | 4922| signatureData | [DataBlob](#datablob) | Yes | Signature data. | 4923 4924**Return value** 4925 4926| Type | Description | 4927| ----------------- | ------------------------------ | 4928| Promise\<[DataBlob](#datablob) \| null> | Promise used to return the data restored.| 4929 4930**Error codes** 4931For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 4932 4933| ID| Error Message | 4934| -------- | ---------------------- | 4935| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 4936| 17620001 | memory error. | 4937| 17620002 | runtime error. | 4938| 17630001 | crypto operation error. | 4939 4940**Example** 4941 4942```ts 4943import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 4944import { buffer } from '@kit.ArkTS'; 4945 4946async function genKeyPairByData(pubKeyData: Uint8Array, priKeyData: Uint8Array) { 4947 let pubKeyBlob: cryptoFramework.DataBlob = { data: pubKeyData }; 4948 let priKeyBlob: cryptoFramework.DataBlob = { data: priKeyData }; 4949 let rsaGenerator = cryptoFramework.createAsyKeyGenerator('RSA1024'); 4950 let keyPair = await rsaGenerator.convertKey(pubKeyBlob, priKeyBlob); 4951 console.info('convertKey success'); 4952 return keyPair; 4953} 4954 4955async function recoverByPromise() { 4956 // Key generated based on the key data and input data for signature verification. If the data in verify() is the same as that in sign(), the signature verification is successful. 4957 let pkData = new Uint8Array([48, 129, 159, 48, 13, 6, 9, 42, 134, 72, 134, 247, 13, 1, 1, 1, 5, 0, 3, 129, 141, 0, 48, 129, 137, 2, 129, 129, 0, 214, 179, 23, 198, 183, 139, 148, 8, 173, 74, 56, 160, 15, 248, 244, 166, 209, 250, 142, 74, 216, 58, 117, 215, 178, 247, 254, 39, 180, 227, 85, 201, 59, 133, 209, 221, 26, 9, 116, 31, 172, 151, 252, 185, 123, 20, 25, 7, 92, 129, 5, 196, 239, 214, 126, 254, 154, 188, 239, 144, 161, 171, 65, 42, 31, 214, 93, 115, 247, 69, 94, 143, 54, 51, 25, 49, 146, 204, 205, 165, 20, 120, 35, 184, 190, 65, 106, 12, 214, 176, 57, 125, 235, 51, 88, 135, 76, 73, 109, 112, 147, 138, 198, 252, 5, 20, 245, 51, 7, 32, 108, 89, 125, 204, 50, 189, 88, 254, 255, 146, 244, 244, 149, 79, 54, 216, 45, 89, 2, 3, 1, 0, 1]); 4958 let skData = new Uint8Array([48, 130, 2, 120, 2, 1, 0, 48, 13, 6, 9, 42, 134, 72, 134, 247, 13, 1, 1, 1, 5, 0, 4, 130, 2, 98, 48, 130, 2, 94, 2, 1, 0, 2, 129, 129, 0, 214, 179, 23, 198, 183, 139, 148, 8, 173, 74, 56, 160, 15, 248, 244, 166, 209, 250, 142, 74, 216, 58, 117, 215, 178, 247, 254, 39, 180, 227, 85, 201, 59, 133, 209, 221, 26, 9, 116, 31, 172, 151, 252, 185, 123, 20, 25, 7, 92, 129, 5, 196, 239, 214, 126, 254, 154, 188, 239, 144, 161, 171, 65, 42, 31, 214, 93, 115, 247, 69, 94, 143, 54, 51, 25, 49, 146, 204, 205, 165, 20, 120, 35, 184, 190, 65, 106, 12, 214, 176, 57, 125, 235, 51, 88, 135, 76, 73, 109, 112, 147, 138, 198, 252, 5, 20, 245, 51, 7, 32, 108, 89, 125, 204, 50, 189, 88, 254, 255, 146, 244, 244, 149, 79, 54, 216, 45, 89, 2, 3, 1, 0, 1, 2, 129, 129, 0, 152, 111, 145, 203, 10, 88, 116, 163, 112, 126, 9, 20, 68, 34, 235, 121, 98, 14, 182, 102, 151, 125, 114, 91, 210, 122, 215, 29, 212, 5, 176, 203, 238, 146, 5, 190, 41, 21, 91, 56, 125, 239, 111, 133, 53, 200, 192, 56, 132, 202, 42, 145, 120, 3, 224, 40, 223, 46, 148, 29, 41, 92, 17, 40, 12, 72, 165, 69, 192, 211, 142, 233, 81, 202, 177, 235, 156, 27, 179, 48, 18, 85, 154, 101, 193, 45, 218, 91, 24, 143, 196, 248, 16, 83, 177, 198, 136, 77, 111, 134, 60, 219, 95, 246, 23, 5, 45, 14, 83, 29, 137, 248, 159, 28, 132, 142, 205, 99, 226, 213, 84, 232, 57, 130, 156, 81, 191, 237, 2, 65, 0, 255, 158, 212, 13, 43, 132, 244, 135, 148, 161, 232, 219, 20, 81, 196, 102, 103, 44, 110, 71, 100, 62, 73, 200, 32, 138, 114, 209, 171, 150, 179, 92, 198, 5, 190, 218, 79, 227, 227, 37, 32, 57, 159, 252, 107, 211, 139, 198, 202, 248, 137, 143, 186, 205, 106, 81, 85, 207, 134, 148, 110, 204, 243, 27, 2, 65, 0, 215, 4, 181, 121, 57, 224, 170, 168, 183, 159, 152, 8, 74, 233, 80, 244, 146, 81, 48, 159, 194, 199, 36, 187, 6, 181, 182, 223, 115, 133, 151, 171, 78, 219, 90, 161, 248, 69, 6, 207, 173, 3, 81, 161, 2, 60, 238, 204, 177, 12, 138, 17, 220, 179, 71, 113, 200, 248, 159, 153, 252, 150, 180, 155, 2, 65, 0, 190, 202, 185, 211, 170, 171, 238, 40, 84, 84, 21, 13, 144, 57, 7, 178, 183, 71, 126, 120, 98, 229, 235, 4, 40, 229, 173, 149, 185, 209, 29, 199, 29, 54, 164, 161, 38, 8, 30, 62, 83, 179, 47, 42, 165, 0, 156, 207, 160, 39, 169, 229, 81, 180, 136, 170, 116, 182, 20, 233, 45, 90, 100, 9, 2, 65, 0, 152, 255, 47, 198, 15, 201, 238, 133, 89, 11, 133, 153, 184, 252, 37, 239, 177, 65, 118, 80, 231, 190, 222, 66, 250, 118, 72, 166, 221, 67, 156, 245, 119, 138, 28, 6, 142, 107, 71, 122, 116, 200, 156, 199, 237, 152, 191, 239, 4, 184, 64, 114, 143, 81, 62, 48, 23, 233, 217, 95, 47, 221, 104, 171, 2, 64, 30, 219, 1, 230, 241, 70, 246, 243, 121, 174, 67, 66, 11, 99, 202, 17, 52, 234, 78, 29, 3, 57, 51, 123, 149, 86, 64, 192, 73, 199, 108, 101, 55, 232, 41, 114, 153, 237, 253, 52, 205, 148, 45, 86, 186, 241, 182, 183, 42, 77, 252, 195, 29, 158, 173, 3, 182, 207, 254, 61, 71, 184, 167, 184]); 4959 let keyPair = await genKeyPairByData(pkData, skData); 4960 // The data is signData.data in Sign(). 4961 let signMessageBlob: cryptoFramework.DataBlob = { data: new Uint8Array([9, 68, 164, 161, 230, 155, 255, 153, 10, 12, 14, 22, 146, 115, 209, 167, 223, 133, 89, 173, 50, 249, 176, 104, 10, 251, 219, 104, 117, 196, 105, 65, 249, 139, 119, 41, 15, 171, 191, 11, 177, 177, 1, 119, 130, 142, 87, 183, 32, 220, 226, 28, 38, 73, 222, 172, 153, 26, 87, 58, 188, 42, 150, 67, 94, 214, 147, 64, 202, 87, 155, 125, 254, 112, 95, 176, 255, 207, 106, 43, 228, 153, 131, 240, 120, 88, 253, 179, 207, 207, 110, 223, 173, 15, 113, 11, 183, 122, 237, 205, 206, 123, 246, 33, 167, 169, 251, 237, 199, 26, 220, 152, 190, 117, 131, 74, 232, 50, 39, 172, 232, 178, 112, 73, 251, 235, 131, 209]) }; 4962 let verifier = cryptoFramework.createVerify('RSA1024|PKCS1|SHA256|Recover'); 4963 await verifier.init(keyPair.pubKey); 4964 try { 4965 let rawSignData = await verifier.recover(signMessageBlob); 4966 if (rawSignData != null) { 4967 console.info('[Promise]: recover result: ' + rawSignData.data); 4968 } else { 4969 console.error("[Promise]: get verify recover result fail!"); 4970 } 4971 } catch (error) { 4972 let e: BusinessError = error as BusinessError; 4973 console.error(`promise error, ${e.code}, ${e.message}`); 4974 } 4975} 4976``` 4977 4978### recoverSync<sup>12+</sup> 4979 4980recoverSync(signatureData: DataBlob): DataBlob | null 4981 4982Recovers the original data from a signature. This API returns the result synchronously. 4983 4984> **NOTE** 4985> 4986> - Currently, only RSA is supported. 4987 4988**Atomic service API**: This API can be used in atomic services since API version 12. 4989 4990**System capability**: SystemCapability.Security.CryptoFramework.Signature 4991 4992**Parameters** 4993 4994| Name | Type | Mandatory| Description | 4995| ------------- | -------- | ---- | ---------- | 4996| signatureData | [DataBlob](#datablob) | Yes | Signature data. | 4997 4998**Return value** 4999 5000| Type | Description | 5001| ----------------- | ------------------------------ | 5002| [DataBlob](#datablob) \| null | Data restored.| 5003 5004**Error codes** 5005For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 5006 5007| ID| Error Message | 5008| -------- | ---------------------- | 5009| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 5010| 17620001 | memory error. | 5011| 17620002 | runtime error. | 5012| 17630001 | crypto operation error. | 5013 5014### setVerifySpec<sup>10+</sup> 5015 5016setVerifySpec(itemType: SignSpecItem, itemValue: number): void 5017 5018setVerifySpec(itemType: SignSpecItem, itemValue: number \| Uint8Array): void 5019 5020Sets signature verification specifications. You can use this API to set signature verification parameters that cannot be set by [createVerify](#cryptoframeworkcreateverify). 5021 5022Currently, only RSA and SM2 are supported. Since API version 11, SM2 signing parameters can be set. 5023 5024The parameters for signature verification must be the same as those for signing. 5025 5026**Atomic service API**: This API can be used in atomic services since API version 12. 5027 5028**System capability**: SystemCapability.Security.CryptoFramework.Signature 5029 5030The supported system capability is SystemCapability.Security.CryptoFramework in API versions 10 to 11 and SystemCapability.Security.CryptoFramework.Signature since API version 12. 5031 5032**Parameters** 5033 5034| Name | Type | Mandatory| Description | 5035| -------- | -------------------- | ---- | ---------- | 5036| itemType | [SignSpecItem](#signspecitem10) | Yes | Signature verification parameter to set.| 5037| itemValue | number \| Uint8Array<sup>11+</sup> | Yes | Value of the signature verification parameter to set.| 5038 5039**Error codes** 5040For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 5041 5042| ID| Error Message | 5043| -------- | ---------------------- | 5044| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 5045| 801 | this operation is not supported. | 5046| 17620001 | memory error. | 5047| 17630001 | crypto operation error. | 5048 5049**Example** 5050 5051<!--code_no_check--> 5052```ts 5053let verifyer: cryptoFramework.Verify; // The process of generating the Verify instance is omitted here. 5054let setN = 20; 5055verifyer.setVerifySpec(cryptoFramework.SignSpecItem.PSS_SALT_LEN_NUM, setN); 5056``` 5057 5058### getVerifySpec<sup>10+</sup> 5059 5060getVerifySpec(itemType: SignSpecItem): string | number 5061 5062Obtains signature verification specifications. Currently, only RSA is supported. 5063 5064The parameters for signature verification must be the same as those for signing. 5065 5066**Atomic service API**: This API can be used in atomic services since API version 12. 5067 5068**System capability**: SystemCapability.Security.CryptoFramework.Signature 5069 5070The supported system capability is SystemCapability.Security.CryptoFramework in API versions 10 to 11 and SystemCapability.Security.CryptoFramework.Signature since API version 12. 5071 5072**Parameters** 5073 5074| Name| Type | Mandatory| Description | 5075| ------ | -------- | ---- | ---------- | 5076| itemType | [SignSpecItem](#signspecitem10) | Yes | Signature verification parameter to obtain.| 5077 5078**Return value** 5079 5080| Type | Description | 5081| -------------- | ----------- | 5082| string \| number | Returns the value of the parameter obtained.| 5083 5084**Error codes** 5085For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 5086 5087| ID| Error Message | 5088| -------- | ---------------------- | 5089| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 5090| 801 | this operation is not supported. | 5091| 17620001 | memory error. | 5092| 17630001 | crypto operation error. | 5093 5094**Example** 5095 5096<!--code_no_check--> 5097```ts 5098let verifyer: cryptoFramework.Verify; // The process of generating the Verify instance is omitted here. 5099let saltLen = verifyer.getVerifySpec(cryptoFramework.SignSpecItem.PSS_SALT_LEN_NUM); 5100``` 5101 5102## cryptoFramework.createKeyAgreement 5103 5104createKeyAgreement(algName: string): KeyAgreement 5105 5106Creates a **KeyAgreement** instance. 5107 5108For details about the supported specifications, see [Key Agreement Overview and Algorithm Specifications](../../security/CryptoArchitectureKit/crypto-key-agreement-overview.md). 5109 5110**Atomic service API**: This API can be used in atomic services since API version 12. 5111 5112**System capability**: SystemCapability.Security.CryptoFramework.KeyAgreement 5113 5114The supported system capability is SystemCapability.Security.CryptoFramework in API versions 9 to 11 and SystemCapability.Security.CryptoFramework.KeyAgreement since API version 12. 5115 5116**Parameters** 5117 5118| Name | Type | Mandatory| Description | 5119| ------- | ------ | ---- | ------------------------------------------------------------ | 5120| algName | string | Yes | Key agreement algorithm to use. In addition to ECC, X25519 and DH are supported since API version 11.| 5121 5122**Return value** 5123 5124| Type | Description | 5125| ------------ | ------------------------------------------ | 5126| KeyAgreement | Returns the **KeyAgreement** instance created.| 5127 5128**Error codes** 5129For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 5130 5131| ID| Error Message | 5132| -------- | ---------------------- | 5133| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 5134| 801 | this operation is not supported. | 5135| 17620001 | memory error. | 5136 5137**Example** 5138 5139```ts 5140import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 5141 5142let keyAgreement = cryptoFramework.createKeyAgreement('ECC256'); 5143``` 5144 5145## KeyAgreement 5146 5147Provides APIs for key agreement operations. Before using any API of the **KeyAgreement** class, you must create a **KeyAgreement** instance by using [createKeyAgreement(algName: string): KeyAgreement](#cryptoframeworkcreatekeyagreement). 5148 5149### Attributes 5150 5151**Atomic service API**: This API can be used in atomic services since API version 12. 5152 5153**System capability**: SystemCapability.Security.CryptoFramework.KeyAgreement 5154 5155The supported system capability is SystemCapability.Security.CryptoFramework in API versions 9 to 11 and SystemCapability.Security.CryptoFramework.KeyAgreement since API version 12. 5156 5157| Name | Type | Readable| Writable| Description | 5158| ------- | ------ | ---- | ---- | ---------------------------- | 5159| algName | string | Yes | No | Algorithm used for key agreement.| 5160 5161### generateSecret 5162 5163generateSecret(priKey: PriKey, pubKey: PubKey, callback: AsyncCallback\<DataBlob>): void 5164 5165Generates a shared secret based on the given private key and public key. This API uses an asynchronous callback to return the shared secret generated. 5166 5167**Atomic service API**: This API can be used in atomic services since API version 12. 5168 5169**System capability**: SystemCapability.Security.CryptoFramework.KeyAgreement 5170 5171The supported system capability is SystemCapability.Security.CryptoFramework in API versions 9 to 11 and SystemCapability.Security.CryptoFramework.KeyAgreement since API version 12. 5172 5173**Parameters** 5174 5175| Name | Type | Mandatory| Description | 5176| -------- | ------------------------ | ---- | ---------------------- | 5177| priKey | [PriKey](#prikey) | Yes | Private key used for key agreement.| 5178| pubKey | [PubKey](#pubkey) | Yes | Public key used for key agreement.| 5179| callback | AsyncCallback\<[DataBlob](#datablob)> | Yes | Callback used to return the shared secret.| 5180 5181**Error codes** 5182For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 5183 5184| ID| Error Message | 5185| -------- | ---------------------- | 5186| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 5187| 17620001 | memory error. | 5188| 17620002 | runtime error. | 5189| 17630001 | crypto operation error. | 5190 5191### generateSecret 5192 5193generateSecret(priKey: PriKey, pubKey: PubKey): Promise\<DataBlob> 5194 5195Generates a shared secret based on the given private key and public key. This API uses a promise to return the shared secret generated. 5196 5197**Atomic service API**: This API can be used in atomic services since API version 12. 5198 5199**System capability**: SystemCapability.Security.CryptoFramework.KeyAgreement 5200 5201The supported system capability is SystemCapability.Security.CryptoFramework in API versions 9 to 11 and SystemCapability.Security.CryptoFramework.KeyAgreement since API version 12. 5202 5203**Parameters** 5204 5205| Name| Type | Mandatory| Description | 5206| ------ | ------ | ---- | ---------------------- | 5207| priKey | [PriKey](#prikey) | Yes | Private key used for key agreement.| 5208| pubKey | [PubKey](#pubkey) | Yes | Public key used for key agreement.| 5209 5210**Return value** 5211 5212| Type | Description | 5213| ------------------ | -------- | 5214| Promise\<[DataBlob](#datablob)> | Promise used to return the shared secret. | 5215 5216**Error codes** 5217For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 5218 5219| ID| Error Message | 5220| -------- | ---------------------- | 5221| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 5222| 17620001 | memory error. | 5223| 17620002 | runtime error. | 5224| 17630001 | crypto operation error. | 5225 5226### generateSecretSync<sup>12+</sup> 5227 5228generateSecretSync(priKey: PriKey, pubKey: PubKey): DataBlob 5229 5230Generates a shared secret based on the given private key and public key. This API returns the shared secret generated synchronously. 5231 5232**Atomic service API**: This API can be used in atomic services since API version 12. 5233 5234**System capability**: SystemCapability.Security.CryptoFramework.KeyAgreement 5235 5236**Parameters** 5237 5238| Name| Type | Mandatory| Description | 5239| ------ | ------ | ---- | ---------------------- | 5240| priKey | [PriKey](#prikey) | Yes | Private key used for key agreement.| 5241| pubKey | [PubKey](#pubkey) | Yes | Public key used for key agreement.| 5242 5243**Return value** 5244 5245| Type | Description | 5246| ------------------ | -------- | 5247|[DataBlob](#datablob) | Shared secret generated.| 5248 5249**Error codes** 5250For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 5251 5252| ID| Error Message | 5253| -------- | ---------------------- | 5254| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 5255| 17620001 | memory error. | 5256| 17620002 | runtime error. | 5257| 17630001 | crypto operation error. | 5258 5259**Example (using the callback-based API)** 5260 5261<!--code_no_check--> 5262```ts 5263import { BusinessError } from '@kit.BasicServicesKit'; 5264 5265let globalKeyPair: cryptoFramework.KeyPair; // globalKeyPair is an asymmetric key object generated by the asymmetric key generator. The generation process is omitted here. 5266let keyAgreement = cryptoFramework.createKeyAgreement('ECC256'); 5267keyAgreement.generateSecret(globalKeyPair.priKey, globalKeyPair.pubKey, (err, secret) => { 5268 if (err) { 5269 console.error("keyAgreement error."); 5270 return; 5271 } 5272 console.info('keyAgreement output is ' + secret.data); 5273}); 5274``` 5275 5276**Example (using the promise-based API)** 5277 5278<!--code_no_check--> 5279```ts 5280import { BusinessError } from '@kit.BasicServicesKit'; 5281 5282let globalKeyPair: cryptoFramework.KeyPair; // globalKeyPair is an asymmetric key object generated by the asymmetric key generator. The generation process is omitted here. 5283let keyAgreement = cryptoFramework.createKeyAgreement('ECC256'); 5284let keyAgreementPromise = keyAgreement.generateSecret(globalKeyPair.priKey, globalKeyPair.pubKey); 5285keyAgreementPromise.then(secret => { 5286 console.info('keyAgreement output is ' + secret.data); 5287}).catch((error: BusinessError) => { 5288 console.error("keyAgreement error."); 5289}); 5290``` 5291 5292**Example (using the sync API)** 5293 5294<!--code_no_check--> 5295```ts 5296let asyGenerator = cryptoFramework.CreateAsyKeyGenerator("ECC256"); 5297let globalKeyPair = asyGenerator.generateKeyPairSync(); 5298let keyAgreement = cryptoFramework.createKeyAgreement('ECC256'); 5299let secret = keyAgreement.generateSecretSync(globalKeyPair.priKey, globalKeyPair.pubKey); 5300console.info("[Sync]keyAgreement output is " + secret.data); 5301``` 5302 5303## cryptoFramework.createMd 5304 5305createMd(algName: string): Md 5306 5307Creates an **Md** instance for MD operations. 5308 5309For details about the supported specifications, see [Supported Algorithms and Specifications](../../security/CryptoArchitectureKit/crypto-generate-message-digest-overview.md#supported-algorithms-and-specifications). 5310 5311**Atomic service API**: This API can be used in atomic services since API version 12. 5312 5313**System capability**: SystemCapability.Security.CryptoFramework.MessageDigest 5314 5315The supported system capability is SystemCapability.Security.CryptoFramework in API versions 9 to 11 and SystemCapability.Security.CryptoFramework.MessageDigest since API version 12. 5316 5317**Parameters** 5318 5319| Name | Type | Mandatory| Description | 5320| ------- | ------ | ---- | ------------------------------------------------------------ | 5321| algName | string | Yes | MD algorithm to use. For details about the supported algorithms, see [Supported Algorithms and Specifications](../../security/CryptoArchitectureKit/crypto-generate-message-digest-overview.md#supported-algorithms-and-specifications).| 5322 5323**Return value** 5324 5325| Type| Description | 5326| ---- | --------------------------------------- | 5327| Md | Returns the [Md](#md) instance created.| 5328 5329**Error codes** 5330For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 5331 5332| ID| Error Message | 5333| -------- | ------------------ | 5334| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 5335| 17620001 | memory error. | 5336 5337**Example** 5338 5339```ts 5340import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 5341import { BusinessError } from '@kit.BasicServicesKit'; 5342 5343try { 5344 // Set algName based on the algorithm supported. 5345 let md = cryptoFramework.createMd('SHA256'); 5346} catch (error) { 5347 let e: BusinessError = error as BusinessError; 5348 console.error(`sync error, ${e.code}, ${e.message}`); 5349} 5350``` 5351 5352## Md 5353 5354Provides APIs for MD operations. Before using any API of the **Md** class, you must create an **Md** instance by using [createMd](#cryptoframeworkcreatemd). 5355 5356### Attributes 5357 5358**Atomic service API**: This API can be used in atomic services since API version 12. 5359 5360**System capability**: SystemCapability.Security.CryptoFramework.MessageDigest 5361 5362The supported system capability is SystemCapability.Security.CryptoFramework in API versions 9 to 11 and SystemCapability.Security.CryptoFramework.MessageDigest since API version 12. 5363 5364| Name | Type | Readable| Writable| Description | 5365| ------- | ------ | ---- | ---- | ---------------------- | 5366| algName | string | Yes | No | Digest algorithm.| 5367 5368### update 5369 5370update(input: DataBlob, callback: AsyncCallback\<void>): void 5371 5372Updates the message for MD operations. This API uses an asynchronous callback to return the result. **update** must be used with **digest** together. **digest** is mandatory, and **update** is optional. 5373 5374> **NOTE** 5375> 5376> - For details about the code for calling **update** multiple times in an MD operation, see [Generating an MD by Passing In Data by Segment](../../security/CryptoArchitectureKit/crypto-generate-message-digest.md#generating-an-md-by-passing-in-data-by-segment). 5377> 5378> - This API does not support wearables. 5379 5380**Atomic service API**: This API can be used in atomic services since API version 12. 5381 5382**System capability**: SystemCapability.Security.CryptoFramework.MessageDigest 5383 5384The supported system capability is SystemCapability.Security.CryptoFramework in API versions 9 to 11 and SystemCapability.Security.CryptoFramework.MessageDigest since API version 12. 5385 5386**Parameters** 5387 5388| Name | Type | Mandatory| Description | 5389| -------- | --------------------- | ---- | ------------ | 5390| input | [DataBlob](#datablob) | Yes | Data to pass in.| 5391| callback | AsyncCallback\<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object. | 5392 5393**Error codes** 5394For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 5395 5396| ID| Error Message | 5397| -------- | ---------------------- | 5398| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 5399| 17630001 | crypto operation error. | 5400 5401### update 5402 5403update(input: DataBlob): Promise\<void> 5404 5405Updates the message for MD operations. This API uses a promise to return the result. **update** must be used with **digest** together. **digest** is mandatory, and **update** is optional. 5406 5407> **NOTE** 5408> 5409> - For details about the code for calling **update** multiple times in an MD operation, see [Generating an MD by Passing In Data by Segment](../../security/CryptoArchitectureKit/crypto-generate-message-digest.md#generating-an-md-by-passing-in-data-by-segment). 5410> 5411> - This API does not support wearables. 5412 5413**Atomic service API**: This API can be used in atomic services since API version 12. 5414 5415**System capability**: SystemCapability.Security.CryptoFramework.MessageDigest 5416 5417The supported system capability is SystemCapability.Security.CryptoFramework in API versions 9 to 11 and SystemCapability.Security.CryptoFramework.MessageDigest since API version 12. 5418 5419| Name| Type | Mandatory| Description | 5420| ------ | -------- | ---- | ------------ | 5421| input | [DataBlob](#datablob) | Yes | Data to pass in.| 5422 5423**Return value** 5424 5425| Type | Description | 5426| -------------- | ------------- | 5427| Promise\<void> | Promise that returns no value.| 5428 5429**Error codes** 5430For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 5431 5432| ID| Error Message | 5433| -------- | ---------------------- | 5434| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 5435| 17630001 | crypto operation error. | 5436 5437### updateSync<sup>12+</sup> 5438 5439updateSync(input: DataBlob): void 5440 5441Updates the message for MD operations. This API returns the result synchronously. **updateSync** must be used with **digestSync** together. **digestSync** is mandatory, and **updateSync** is optional. 5442 5443> **NOTE** 5444> 5445> For details about the code for calling **updateSync** multiple times in an MD operation, see [Generating an MD by Passing In Data by Segment](../../security/CryptoArchitectureKit/crypto-generate-message-digest.md#generating-an-md-by-passing-in-data-by-segment). 5446 5447**Atomic service API**: This API can be used in atomic services since API version 12. 5448 5449**System capability**: SystemCapability.Security.CryptoFramework.MessageDigest 5450 5451| Name| Type | Mandatory| Description | 5452| ------ | -------- | ---- | ------------ | 5453| input | [DataBlob](#datablob) | Yes | Data to pass in.| 5454 5455**Return value** 5456 5457| Type | Description | 5458| -------------- | ------------- | 5459| void | No value is returned.| 5460 5461**Error codes** 5462For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 5463 5464| ID| Error Message | 5465| -------- | ---------------------- | 5466| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed. | 5467| 17630001 | crypto operation error. | 5468 5469### digest 5470 5471digest(callback: AsyncCallback\<DataBlob>): void 5472 5473Generates an MD. This API uses an asynchronous callback to return the result. 5474 5475> **NOTE** 5476> 5477> This API does not support wearables. 5478 5479**Atomic service API**: This API can be used in atomic services since API version 12. 5480 5481**System capability**: SystemCapability.Security.CryptoFramework.MessageDigest 5482 5483The supported system capability is SystemCapability.Security.CryptoFramework in API versions 9 to 11 and SystemCapability.Security.CryptoFramework.MessageDigest since API version 12. 5484 5485| Name | Type | Mandatory| Description | 5486| -------- | ------------------------ | ---- | ---------- | 5487| callback | AsyncCallback\<[DataBlob](#datablob)> | Yes | Callback invoked to return a **DataBlob** object.| 5488 5489**Error codes** 5490For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 5491 5492| ID| Error Message | 5493| -------- | ---------------------- | 5494| 17620001 | memory error. | 5495| 17630001 | crypto operation error. | 5496 5497**Example** 5498 5499```ts 5500import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 5501import { buffer } from '@kit.ArkTS'; 5502 5503function mdByCallback() { 5504 let md = cryptoFramework.createMd('SHA256'); 5505 md.update({ data: new Uint8Array(buffer.from("mdTestMessage", 'utf-8').buffer) }, (err,) => { 5506 md.digest((err, digestOutput) => { 5507 console.info('[Callback]: MD result: ' + digestOutput.data); 5508 console.info('[Callback]: MD len: ' + md.getMdLength()); 5509 }); 5510 }); 5511} 5512``` 5513 5514### digest 5515 5516digest(): Promise\<DataBlob> 5517 5518Generates an MD. This API uses a promise to return the result. 5519 5520> **NOTE** 5521> 5522> This API does not support wearables. 5523 5524**Atomic service API**: This API can be used in atomic services since API version 12. 5525 5526**System capability**: SystemCapability.Security.CryptoFramework.MessageDigest 5527 5528The supported system capability is SystemCapability.Security.CryptoFramework in API versions 9 to 11 and SystemCapability.Security.CryptoFramework.MessageDigest since API version 12. 5529 5530**Return value** 5531 5532| Type | Description | 5533| ------------------ | ----------- | 5534| Promise\<[DataBlob](#datablob)> | Promise used to return the result.| 5535 5536**Error codes** 5537For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 5538 5539| ID| Error Message | 5540| -------- | ---------------------- | 5541| 17620001 | memory error. | 5542| 17630001 | crypto operation error. | 5543 5544**Example** 5545 5546```ts 5547import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 5548import { buffer } from '@kit.ArkTS'; 5549 5550async function mdByPromise() { 5551 let md = cryptoFramework.createMd('SHA256'); 5552 await md.update({ data: new Uint8Array(buffer.from("mdTestMessage", 'utf-8').buffer) }); 5553 let mdOutput = await md.digest(); 5554 console.info('[Promise]: MD result: ' + mdOutput.data); 5555 console.info('[Promise]: MD len: ' + md.getMdLength()); 5556} 5557``` 5558 5559### digestSync<sup>12+</sup> 5560 5561digestSync(): DataBlob 5562 5563Generates an MD. This API returns the result synchronously. 5564 5565**Atomic service API**: This API can be used in atomic services since API version 12. 5566 5567**System capability**: SystemCapability.Security.CryptoFramework.MessageDigest 5568 5569**Return value** 5570 5571| Type | Description | 5572| ------------------ | ----------- | 5573| [DataBlob](#datablob) | MD generated.| 5574 5575**Error codes** 5576For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 5577 5578| ID| Error Message | 5579| -------- | ---------------------- | 5580| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed. | 5581| 17620001 | memory error. | 5582| 17620002 | runtime error. | 5583| 17630001 | crypto operation error. | 5584 5585**Example** 5586 5587```ts 5588import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 5589import { buffer } from '@kit.ArkTS'; 5590 5591async function mdBySync() { 5592 let md = cryptoFramework.createMd('SHA256'); 5593 md.updateSync({ data: new Uint8Array(buffer.from("mdTestMessage", 'utf-8').buffer) }); 5594 let mdOutput = md.digestSync(); 5595 console.info('[Sync]: MD result: ' + mdOutput.data); 5596 console.info('[Sync]: MD len: ' + md.getMdLength()); 5597} 5598``` 5599 5600### getMdLength 5601 5602getMdLength(): number 5603 5604Obtains the MD length, in bytes. 5605 5606**Atomic service API**: This API can be used in atomic services since API version 12. 5607 5608**System capability**: SystemCapability.Security.CryptoFramework.MessageDigest 5609 5610The supported system capability is SystemCapability.Security.CryptoFramework in API versions 9 to 11 and SystemCapability.Security.CryptoFramework.MessageDigest since API version 12. 5611 5612**Return value** 5613 5614| Type | Description | 5615| ------ | -------------------------- | 5616| number | MD length obtained.| 5617 5618**Error codes** 5619For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 5620 5621| ID| Error Message | 5622| -------- | ---------------------- | 5623| 17630001 | crypto operation error. | 5624 5625**Example** 5626 5627```ts 5628import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 5629 5630function getLength() { 5631 let md = cryptoFramework.createMd('SHA256'); 5632 console.info('[Promise]: MD len: ' + md.getMdLength()); 5633} 5634``` 5635 5636## cryptoFramework.createMac 5637 5638createMac(algName: string): Mac 5639 5640Creates a **Mac** instance for MAC operations. 5641 5642For details about the supported specifications, see [HMAC](../../security/CryptoArchitectureKit/crypto-compute-mac-overview.md#hmac). 5643 5644**Atomic service API**: This API can be used in atomic services since API version 12. 5645 5646**System capability**: SystemCapability.Security.CryptoFramework.Mac 5647 5648The supported system capability is SystemCapability.Security.CryptoFramework in API versions 9 to 11 and SystemCapability.Security.CryptoFramework.Mac since API version 12. 5649 5650**Parameters** 5651 5652| Name | Type | Mandatory| Description | 5653| ------- | ------ | ---- | ------------------------------------------------------------ | 5654| algName | string | Yes | MD algorithm to use. For details about the supported algorithms, see [HMAC](../../security/CryptoArchitectureKit/crypto-compute-mac-overview.md#hmac).| 5655 5656**Return value** 5657 5658| Type| Description | 5659| ---- | ----------------------------------------- | 5660| Mac | Returns the [Mac](#mac) instance created.| 5661 5662**Error codes** 5663For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 5664 5665| ID| Error Message | 5666| -------- | ------------------ | 5667| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 5668| 17620001 | memory error. | 5669 5670**Example** 5671 5672```ts 5673import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 5674import { BusinessError } from '@kit.BasicServicesKit'; 5675 5676try { 5677 // Set algName based on the algorithm supported. 5678 let mac = cryptoFramework.createMac('SHA256'); 5679} catch (error) { 5680 let e: BusinessError = error as BusinessError; 5681 console.error(`sync error, ${e.code}, ${e.message}`); 5682} 5683``` 5684 5685## cryptoFramework.createMac<sup>18+</sup> 5686 5687createMac(macSpec: MacSpec): Mac 5688 5689Creates a **Mac** instance for MAC operations. 5690 5691For details about the supported specifications, see [MAC Overview and Algorithm Specifications](../../security/CryptoArchitectureKit/crypto-compute-mac-overview.md#mac-overview-and-algorithm-specifications). 5692 5693**Atomic service API**: This API can be used in atomic services since API version 18. 5694 5695**System capability**: SystemCapability.Security.CryptoFramework.Mac 5696 5697**Parameters** 5698 5699| Name | Type | Mandatory| Description | 5700| ------- | ------ | ---- | ------------------------------------------------------------ | 5701| macSpec | [MacSpec](#macspec18) | Yes | MAC specifications, which vary depending on the MAC to generate. For details about the supported algorithms, see [MAC Overview and Algorithm Specifications](../../security/CryptoArchitectureKit/crypto-compute-mac-overview.md#mac-overview-and-algorithm-specifications).| 5702 5703**Return value** 5704 5705| Type| Description | 5706| ---- | ----------------------------------------- | 5707| Mac | [Mac](#mac) instance created.| 5708 5709**Error codes** 5710For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 5711 5712| ID| Error Message | 5713| -------- | ------------------ | 5714| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 5715| 17620001 | memory error. | 5716| 17620002 | runtime error. | 5717| 17630001 | crypto operation error. | 5718 5719**Example** 5720 5721```ts 5722import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 5723import { BusinessError } from '@kit.BasicServicesKit'; 5724 5725try { 5726 // Set algName based on the algorithm supported. 5727 let spec: cryptoFramework.HmacSpec = { 5728 algName: "HMAC", 5729 mdName: "SHA256", 5730 }; 5731 let mac = cryptoFramework.createMac(spec); 5732} catch (error) { 5733 let e: BusinessError = error as BusinessError; 5734 console.error(`sync error, ${e.code}, ${e.message}`); 5735} 5736``` 5737 5738## Mac 5739 5740Provides APIs for MAC operations. Before using any API of the **Mac** class, you must create a **Mac** instance by using [createMac](#cryptoframeworkcreatemac). 5741 5742### Attributes 5743 5744**Atomic service API**: This API can be used in atomic services since API version 12. 5745 5746**System capability**: SystemCapability.Security.CryptoFramework.Mac 5747 5748The supported system capability is SystemCapability.Security.CryptoFramework in API versions 9 to 11 and SystemCapability.Security.CryptoFramework.Mac since API version 12. 5749 5750| Name | Type | Readable| Writable| Description | 5751| ------- | ------ | ---- | ---- | ---------------------- | 5752| algName | string | Yes | No | Digest algorithm.| 5753 5754### init 5755 5756init(key: SymKey, callback: AsyncCallback\<void>): void 5757 5758Initializes the MAC computation with a symmetric key. This API uses an asynchronous callback to return the result. **init**, **update**, and **doFinal** must be used together. **init** and **doFinal** are mandatory, and **update** is optional. 5759 5760 > **NOTE** 5761 > 5762 > You are advised to create a symmetric key generator based on the [HMAC key generation specifications](../../security/CryptoArchitectureKit/crypto-sym-key-generation-conversion-spec.md#hmac) and use [generateSymKey](#generatesymkey) to randomly generate a symmetric key or use [convertKey](#convertkey) to convert the binary data (whose length is the same as the key specifications) into a key.<br>If **HMAC** is specified to generate the symmetric key generator, only [convertKey](#convertkey) can be called to pass in a binary key of 1 to 4096 bytes. 5763 5764**Atomic service API**: This API can be used in atomic services since API version 12. 5765 5766**System capability**: SystemCapability.Security.CryptoFramework.Mac 5767 5768The supported system capability is SystemCapability.Security.CryptoFramework in API versions 9 to 11 and SystemCapability.Security.CryptoFramework.Mac since API version 12. 5769 5770**Parameters** 5771 5772| Name | Type | Mandatory| Description | 5773| -------- | -------------------- | ---- | -------------- | 5774| key | [SymKey](#symkey) | Yes | Shared symmetric key.| 5775| callback | AsyncCallback\<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object. | 5776 5777**Error codes** 5778For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 5779 5780| ID| Error Message | 5781| -------- | ---------------------- | 5782| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 5783| 17630001 | crypto operation error. | 5784 5785### init 5786 5787init(key: SymKey): Promise\<void> 5788 5789Initializes the MAC computation with a symmetric key. This API uses a promise to return the result. **init**, **update**, and **doFinal** must be used together. **init** and **doFinal** are mandatory, and **update** is optional. 5790 5791**Atomic service API**: This API can be used in atomic services since API version 12. 5792 5793**System capability**: SystemCapability.Security.CryptoFramework.Mac 5794 5795The supported system capability is SystemCapability.Security.CryptoFramework in API versions 9 to 11 and SystemCapability.Security.CryptoFramework.Mac since API version 12. 5796 5797**Parameters** 5798 5799| Name| Type | Mandatory| Description | 5800| ------ | ------ | ---- | ------------ | 5801| key | [SymKey](#symkey) | Yes | Shared symmetric key.| 5802 5803**Return value** 5804 5805| Type | Description | 5806| -------------- | ------------- | 5807| Promise\<void> | Promise that returns no value.| 5808 5809**Error codes** 5810For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 5811 5812| ID| Error Message | 5813| -------- | ---------------------- | 5814| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 5815| 17630001 | crypto operation error. | 5816 5817### initSync<sup>12+</sup> 5818 5819initSync(key: SymKey): void 5820 5821Initializes the MAC computation with a symmetric key. This API returns the result synchronously. **initSync**, **updateSync**, and **doFinalSync** must be used together. **initSync** and **doFinalSync** are mandatory, and **updateSync** is optional. 5822 5823**Atomic service API**: This API can be used in atomic services since API version 12. 5824 5825**System capability**: SystemCapability.Security.CryptoFramework.Mac 5826 5827**Parameters** 5828 5829| Name| Type | Mandatory| Description | 5830| ------ | ------ | ---- | ------------ | 5831| key | [SymKey](#symkey) | Yes | Shared symmetric key.| 5832 5833**Return value** 5834 5835| Type | Description | 5836| -------------- | ------------- | 5837| void | No value is returned.| 5838 5839**Error codes** 5840For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 5841 5842| ID| Error Message | 5843| -------- | ---------------------- | 5844| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed. | 5845| 17630001 | crypto operation error. | 5846 5847### update 5848 5849update(input: DataBlob, callback: AsyncCallback\<void>): void 5850 5851Updates the message for MAC computation. This API uses an asynchronous callback to return the result. 5852 5853> **NOTE** 5854> 5855> For details about the sample code for calling **update** multiple times in an HMAC operation, see [Generating an HMAC by Passing In Data by Segment](../../security/CryptoArchitectureKit/crypto-compute-hmac.md#generating-an-hmac-by-passing-in-data-by-segment). 5856 5857**Atomic service API**: This API can be used in atomic services since API version 12. 5858 5859**System capability**: SystemCapability.Security.CryptoFramework.Mac 5860 5861The supported system capability is SystemCapability.Security.CryptoFramework in API versions 9 to 11 and SystemCapability.Security.CryptoFramework.Mac since API version 12. 5862 5863**Parameters** 5864 5865| Name | Type | Mandatory| Description | 5866| -------- | --------------------- | ---- | ------------ | 5867| input | [DataBlob](#datablob) | Yes | Data to pass in.| 5868| callback | AsyncCallback\<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.| 5869 5870**Error codes** 5871For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 5872 5873| ID| Error Message | 5874| -------- | ---------------------- | 5875| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 5876| 17630001 | crypto operation error. | 5877 5878### update 5879 5880update(input: DataBlob): Promise\<void> 5881 5882Updates the message for MAC computation. This API uses a promise to return the result. 5883 5884> **NOTE** 5885> 5886> For details about the sample code for calling **update** multiple times in an HMAC operation, see [Generating an HMAC by Passing In Data by Segment](../../security/CryptoArchitectureKit/crypto-compute-hmac.md#generating-an-hmac-by-passing-in-data-by-segment). 5887 5888**Atomic service API**: This API can be used in atomic services since API version 12. 5889 5890**System capability**: SystemCapability.Security.CryptoFramework.Mac 5891 5892The supported system capability is SystemCapability.Security.CryptoFramework in API versions 9 to 11 and SystemCapability.Security.CryptoFramework.Mac since API version 12. 5893 5894**Parameters** 5895 5896| Name| Type | Mandatory| Description | 5897| ------ | -------- | ---- | ---------- | 5898| input | [DataBlob](#datablob) | Yes | Data to pass in.| 5899 5900**Return value** 5901 5902| Type | Description | 5903| -------------- | ------------- | 5904| Promise\<void> | Promise that returns no value.| 5905 5906**Error codes** 5907For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 5908 5909| ID| Error Message | 5910| -------- | ---------------------- | 5911| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 5912| 17630001 | crypto operation error. | 5913 5914### updateSync<sup>12+</sup> 5915 5916updateSync(input: DataBlob): void 5917 5918Updates the message for MAC computation. This API returns the result synchronously. 5919 5920> **NOTE** 5921> 5922> For details about the sample code for calling **updateSync** multiple times in an HMAC operation, see [Generating an HMAC by Passing In Data by Segment](../../security/CryptoArchitectureKit/crypto-compute-hmac.md#generating-an-hmac-by-passing-in-data-by-segment). 5923 5924**Atomic service API**: This API can be used in atomic services since API version 12. 5925 5926**System capability**: SystemCapability.Security.CryptoFramework.Mac 5927 5928**Parameters** 5929 5930| Name| Type | Mandatory| Description | 5931| ------ | -------- | ---- | ---------- | 5932| input | [DataBlob](#datablob) | Yes | Data to pass in.| 5933 5934**Return value** 5935 5936| Type | Description | 5937| -------------- | ------------- | 5938| void | No value is returned.| 5939 5940**Error codes** 5941For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 5942 5943| ID| Error Message | 5944| -------- | ---------------------- | 5945| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed. | 5946| 17630001 | crypto operation error. | 5947 5948### doFinal 5949 5950doFinal(callback: AsyncCallback\<DataBlob>): void 5951 5952Finishes the MAC computation. This API uses an asynchronous callback to return the result. 5953 5954**Atomic service API**: This API can be used in atomic services since API version 12. 5955 5956**System capability**: SystemCapability.Security.CryptoFramework.Mac 5957 5958The supported system capability is SystemCapability.Security.CryptoFramework in API versions 9 to 11 and SystemCapability.Security.CryptoFramework.Mac since API version 12. 5959 5960**Parameters** 5961 5962| Name | Type | Mandatory| Description | 5963| -------- | ------------------------ | ---- | -------- | 5964| callback | AsyncCallback\<[DataBlob](#datablob)> | Yes | Callback invoked to return a **DataBlob** object.| 5965 5966**Error codes** 5967For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 5968 5969| ID| Error Message | 5970| -------- | ---------------------- | 5971| 17620001 | memory error. | 5972| 17630001 | crypto operation error. | 5973 5974**Example** 5975 5976For more HMAC operation examples, see [Generating an HMAC by Passing In Data by Segment](../../security/CryptoArchitectureKit/crypto-compute-hmac.md#generating-an-hmac-by-passing-in-data-by-segment). 5977 5978```ts 5979import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 5980import { buffer } from '@kit.ArkTS'; 5981 5982function hmacByCallback() { 5983 let mac = cryptoFramework.createMac('SHA256'); 5984 let keyBlob: cryptoFramework.DataBlob = { data: new Uint8Array(buffer.from("12345678abcdefgh", 'utf-8').buffer) }; 5985 let symKeyGenerator = cryptoFramework.createSymKeyGenerator('AES128'); 5986 symKeyGenerator.convertKey(keyBlob, (err, symKey) => { 5987 mac.init(symKey, (err,) => { 5988 mac.update({ data: new Uint8Array(buffer.from("hmacTestMessage", 'utf-8').buffer) }, (err,) => { 5989 mac.doFinal((err, output) => { 5990 console.info('[Callback]: HMAC result: ' + output.data); 5991 console.info('[Callback]: MAC len: ' + mac.getMacLength()); 5992 }); 5993 }); 5994 }); 5995 }); 5996} 5997``` 5998 5999### doFinal 6000 6001doFinal(): Promise\<DataBlob> 6002 6003Finishes the MAC computation. This API uses a promise to return the result. 6004 6005**Atomic service API**: This API can be used in atomic services since API version 12. 6006 6007**System capability**: SystemCapability.Security.CryptoFramework.Mac 6008 6009The supported system capability is SystemCapability.Security.CryptoFramework in API versions 9 to 11 and SystemCapability.Security.CryptoFramework.Mac since API version 12. 6010 6011**Return value** 6012 6013| Type | Description | 6014| ------------------ | ----------- | 6015| Promise\<[DataBlob](#datablob)> | Promise used to return the result.| 6016 6017**Error codes** 6018For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 6019 6020| ID| Error Message | 6021| -------- | ---------------------- | 6022| 17620001 | memory error. | 6023| 17630001 | crypto operation error. | 6024 6025**Example** 6026 6027For more HMAC operation examples, see [Generating an HMAC by Passing In Data by Segment](../../security/CryptoArchitectureKit/crypto-compute-hmac.md#generating-an-hmac-by-passing-in-data-by-segment). 6028 6029```ts 6030import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 6031import { buffer } from '@kit.ArkTS'; 6032 6033async function hmacByPromise() { 6034 let mac = cryptoFramework.createMac('SHA256'); 6035 let keyBlob: cryptoFramework.DataBlob = { data: new Uint8Array(buffer.from("12345678abcdefgh", 'utf-8').buffer) }; 6036 let symKeyGenerator = cryptoFramework.createSymKeyGenerator('AES128'); 6037 let symKey = await symKeyGenerator.convertKey(keyBlob); 6038 await mac.init(symKey); 6039 await mac.update({ data: new Uint8Array(buffer.from("hmacTestMessage", 'utf-8').buffer) }); 6040 let macOutput = await mac.doFinal(); 6041 console.info('[Promise]: HMAC result: ' + macOutput.data); 6042 console.info('[Promise]: MAC len: ' + mac.getMacLength()); 6043} 6044``` 6045 6046### doFinalSync<sup>12+</sup> 6047 6048doFinalSync(): DataBlob 6049 6050Finishes the MAC computation. This API returns the result synchronously. 6051 6052**Atomic service API**: This API can be used in atomic services since API version 12. 6053 6054**System capability**: SystemCapability.Security.CryptoFramework.Mac 6055 6056**Return value** 6057 6058| Type | Description | 6059| ------------------ | ----------- | 6060| [DataBlob](#datablob) | MAC computation result.| 6061 6062**Error codes** 6063For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 6064 6065| ID| Error Message | 6066| -------- | ---------------------- | 6067| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed. | 6068| 17620001 | memory error. | 6069| 17620002 | runtime error. | 6070| 17630001 | crypto operation error. | 6071 6072**Example** 6073 6074For more HMAC operation examples, see [Generating an HMAC by Passing In Data by Segment](../../security/CryptoArchitectureKit/crypto-compute-hmac.md#generating-an-hmac-by-passing-in-data-by-segment). 6075 6076```ts 6077import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 6078import { buffer } from '@kit.ArkTS'; 6079 6080function hmacBySync() { 6081 let mac = cryptoFramework.createMac('SHA256'); 6082 let keyBlob: cryptoFramework.DataBlob = { data: new Uint8Array(buffer.from("12345678abcdefgh", 'utf-8').buffer) }; 6083 let symKeyGenerator = cryptoFramework.createSymKeyGenerator('AES128'); 6084 let symKey = symKeyGenerator.convertKeySync(keyBlob); 6085 mac.initSync(symKey); 6086 mac.updateSync({ data: new Uint8Array(buffer.from("hmacTestMessage", 'utf-8').buffer) }); 6087 let macOutput = mac.doFinalSync(); 6088 console.info('[Sync]: HMAC result: ' + macOutput.data); 6089 console.info('[Sync]: MAC len: ' + mac.getMacLength()); 6090} 6091``` 6092 6093### getMacLength 6094 6095getMacLength(): number 6096 6097Obtains the MAC length, in bytes. 6098 6099**Atomic service API**: This API can be used in atomic services since API version 12. 6100 6101**System capability**: SystemCapability.Security.CryptoFramework.Mac 6102 6103The supported system capability is SystemCapability.Security.CryptoFramework in API versions 9 to 11 and SystemCapability.Security.CryptoFramework.Mac since API version 12. 6104 6105**Return value** 6106 6107| Type | Description | 6108| ------ | --------------------------- | 6109| number | MAC length obtained.| 6110 6111**Error codes** 6112For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 6113 6114| ID| Error Message | 6115| -------- | ---------------------- | 6116| 17630001 | crypto operation error. | 6117 6118**Example** 6119 6120<!--code_no_check--> 6121```ts 6122import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 6123import { BusinessError } from '@kit.BasicServicesKit'; 6124 6125let mac = cryptoFramework.createMac('SHA256'); 6126console.info('Mac algName is: ' + mac.algName); 6127let keyData = new Uint8Array([83, 217, 231, 76, 28, 113, 23, 219, 250, 71, 209, 210, 205, 97, 32, 159]); 6128let keyBlob: cryptoFramework.DataBlob = { data: keyData }; 6129let symKeyGenerator = cryptoFramework.createSymKeyGenerator('AES128'); 6130let promiseConvertKey = symKeyGenerator.convertKey(keyBlob); 6131promiseConvertKey.then(symKey => { 6132 let promiseMacInit = mac.init(symKey); 6133 return promiseMacInit; 6134}).then(() => { 6135 let blob: cryptoFramework.DataBlob = { data : new Uint8Array([83])}; 6136 let promiseMacUpdate = mac.update(blob); 6137 return promiseMacUpdate; 6138}).then(() => { 6139 let promiseMacDoFinal = mac.doFinal(); 6140 return promiseMacDoFinal; 6141}).then(macOutput => { 6142 console.info('[Promise]: HMAC result: ' + macOutput.data); 6143 let macLen = mac.getMacLength(); 6144 console.info('MAC len: ' + macLen); 6145}).catch((error: BusinessError) => { 6146 console.error("[Promise]: error: " + error.message); 6147}); 6148``` 6149 6150## cryptoFramework.createRandom 6151 6152createRandom(): Random 6153 6154Creates a **Random** instance for generating random numbers and setting seeds. 6155 6156For details about the supported specifications, see [Supported Algorithms and Specifications](../../security/CryptoArchitectureKit/crypto-generate-random-number.md#supported-algorithms-and-specifications). 6157 6158**Atomic service API**: This API can be used in atomic services since API version 11. 6159 6160**System capability**: SystemCapability.Security.CryptoFramework.Rand 6161 6162The supported system capability is SystemCapability.Security.CryptoFramework in API versions 9 to 11 and SystemCapability.Security.CryptoFramework.Rand since API version 12. 6163 6164**Return value** 6165 6166| Type | Description | 6167| ------ | ----------------------------------------------- | 6168| Random | Returns the [Random](#random) instance created.| 6169 6170**Error codes** 6171For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 6172 6173| ID| Error Message | 6174| -------- | ------------ | 6175| 17620001 | memory error. | 6176 6177**Example** 6178 6179```ts 6180import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 6181import { BusinessError } from '@kit.BasicServicesKit'; 6182 6183try { 6184 let rand = cryptoFramework.createRandom(); 6185} catch (error) { 6186 let e: BusinessError = error as BusinessError; 6187 console.error(`sync error, ${e.code}, ${e.message}`); 6188} 6189``` 6190 6191## Random 6192 6193Provides 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). 6194 6195### Attributes 6196 6197**Atomic service API**: This API can be used in atomic services since API version 11. 6198 6199**System capability**: SystemCapability.Security.CryptoFramework.Rand 6200 6201The supported system capability is SystemCapability.Security.CryptoFramework in API versions 9 to 11 and SystemCapability.Security.CryptoFramework.Rand since API version 12. 6202 6203| Name | Type | Readable| Writable| Description | 6204| ------- | ------ | ---- | ---- | -------------------- | 6205| algName<sup>10+</sup> | string | Yes | No | Algorithm used to generate the random number. Currently, only **CTR_DRBG** is supported.| 6206 6207### generateRandom 6208 6209generateRandom(len: number, callback: AsyncCallback\<DataBlob>): void 6210 6211Generates a random number of the specified length. This API uses an asynchronous callback to return the result. 6212 6213> **NOTE** 6214> 6215> This API does not support wearables. 6216 6217**Atomic service API**: This API can be used in atomic services since API version 11. 6218 6219**System capability**: SystemCapability.Security.CryptoFramework.Rand 6220 6221The supported system capability is SystemCapability.Security.CryptoFramework in API versions 9 to 11 and SystemCapability.Security.CryptoFramework.Rand since API version 12. 6222 6223**Parameters** 6224 6225| Name | Type | Mandatory| Description | 6226| -------- | ------------------------ | ---- | -------------------- | 6227| len | number | Yes | Length of the random number to generate, in bytes. The value range is [1, INT_MAX].| 6228| callback | AsyncCallback\<[DataBlob](#datablob)> | Yes | Callback invoked to return a **DataBlob** object.| 6229 6230**Error codes** 6231For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 6232 6233| ID| Error Message | 6234| -------- | ---------------------- | 6235| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 6236| 17620001 | memory error. | 6237| 17630001 | crypto operation error. | 6238 6239**Example** 6240 6241```ts 6242import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 6243 6244let rand = cryptoFramework.createRandom(); 6245rand.generateRandom(12, (err, randData) => { 6246 if (err) { 6247 console.error("[Callback] err: " + err.code); 6248 } else { 6249 console.info('[Callback]: generate random result: ' + randData.data); 6250 } 6251}); 6252``` 6253 6254### generateRandom 6255 6256generateRandom(len: number): Promise\<DataBlob> 6257 6258Generates a random number of the specified length. This API uses a promise to return the result. 6259 6260> **NOTE** 6261> 6262> This API does not support wearables. 6263 6264**Atomic service API**: This API can be used in atomic services since API version 11. 6265 6266**System capability**: SystemCapability.Security.CryptoFramework.Rand 6267 6268The supported system capability is SystemCapability.Security.CryptoFramework in API versions 9 to 11 and SystemCapability.Security.CryptoFramework.Rand since API version 12. 6269 6270**Parameters** 6271 6272| Name| Type | Mandatory| Description | 6273| ------ | ------ | ---- | ------------------------------------------------------ | 6274| len | number | Yes | Length of the random number to generate, in bytes. The value range is [1, INT_MAX].| 6275 6276**Return value** 6277 6278| Type | Description | 6279| ------------------ | ----------- | 6280| Promise\<[DataBlob](#datablob)> | Promise used to return the result.| 6281 6282**Error codes** 6283For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 6284 6285| ID| Error Message | 6286| -------- | ---------------------- | 6287| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 6288| 17620001 | memory error. | 6289| 17630001 | crypto operation error. | 6290 6291**Example** 6292 6293```ts 6294import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 6295import { BusinessError } from '@kit.BasicServicesKit'; 6296 6297let rand = cryptoFramework.createRandom(); 6298let promiseGenerateRand = rand.generateRandom(12); 6299promiseGenerateRand.then(randData => { 6300 console.info('[Promise]: rand result: ' + randData.data); 6301}).catch((error: BusinessError) => { 6302 console.error("[Promise]: error: " + error.message); 6303}); 6304``` 6305 6306### generateRandomSync<sup>10+</sup> 6307 6308generateRandomSync(len: number): DataBlob 6309 6310Generates a random number of the specified length. This API returns the result synchronously. 6311 6312**Atomic service API**: This API can be used in atomic services since API version 11. 6313 6314**System capability**: SystemCapability.Security.CryptoFramework.Rand 6315 6316The supported system capability is SystemCapability.Security.CryptoFramework in API versions 10 to 11 and SystemCapability.Security.CryptoFramework.Rand since API version 12. 6317 6318**Parameters** 6319 6320| Name| Type | Mandatory| Description | 6321| ------ | ------ | ---- | -------------------- | 6322| len | number | Yes | Length of the random number to generate, in bytes. The value range is [1, INT_MAX].| 6323 6324**Return value** 6325 6326| Type | Description | 6327| ------------------ | ----------- | 6328|[DataBlob](#datablob) | Returns the generated random number.| 6329 6330**Error codes** 6331For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 6332 6333| ID| Error Message | 6334| -------- | ---------------------- | 6335| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 6336| 17620001 | memory error. | 6337| 17630001 | crypto operation error. | 6338 6339**Example** 6340 6341```ts 6342import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 6343import { BusinessError } from '@kit.BasicServicesKit'; 6344 6345let rand = cryptoFramework.createRandom(); 6346try { 6347 let randData = rand.generateRandomSync(12); 6348 if (randData != null) { 6349 console.info('[Sync]: rand result: ' + randData.data); 6350 } else { 6351 console.error("[Sync]: get rand result fail!"); 6352 } 6353} catch (error) { 6354 let e: BusinessError = error as BusinessError; 6355 console.error(`sync error, ${e.code}, ${e.message}`); 6356} 6357``` 6358 6359### setSeed 6360 6361setSeed(seed: DataBlob): void 6362 6363Sets a seed. 6364 6365**Atomic service API**: This API can be used in atomic services since API version 11. 6366 6367**System capability**: SystemCapability.Security.CryptoFramework.Rand 6368 6369The supported system capability is SystemCapability.Security.CryptoFramework in API versions 9 to 11 and SystemCapability.Security.CryptoFramework.Rand since API version 12. 6370 6371| Name| Type | Mandatory| Description | 6372| ------ | -------- | ---- | ------------ | 6373| seed | [DataBlob](#datablob) | Yes | Seed to set.| 6374 6375**Error codes** 6376For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 6377 6378| ID| Error Message | 6379| -------- | ----------------- | 6380| 17620001 | memory error. | 6381 6382**Example** 6383 6384```ts 6385import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 6386import { BusinessError } from '@kit.BasicServicesKit'; 6387 6388let rand = cryptoFramework.createRandom(); 6389rand.generateRandom(12, (err, randData) => { 6390 if (err) { 6391 console.error("[Callback] err: " + err.code); 6392 } else { 6393 console.info('[Callback]: generate random result: ' + randData.data); 6394 try { 6395 rand.setSeed(randData); 6396 } catch (error) { 6397 let e: BusinessError = error as BusinessError; 6398 console.error(`sync error, ${e.code}, ${e.message}`); 6399 } 6400 } 6401}); 6402``` 6403 6404## cryptoFramework.createKdf<sup>11+</sup> 6405 6406createKdf(algName: string): Kdf 6407 6408Creates a key derivation function instance.<br>For details about the supported specifications, see [Key Derivation Overview and Algorithm Specifications](../../security/CryptoArchitectureKit/crypto-key-derivation-overview.md). 6409 6410**Atomic service API**: This API can be used in atomic services since API version 12. 6411 6412**System capability**: SystemCapability.Security.CryptoFramework.Kdf 6413 6414The supported system capability is SystemCapability.Security.CryptoFramework in API version 11 and SystemCapability.Security.CryptoFramework.Kdf since API version 12. 6415 6416**Parameters** 6417 6418| Name | Type | Mandatory| Description | 6419| ------- | ------ | ---- | --------------------------------- | 6420| algName | string | Yes | Key derivation algorithm (including the hash function for the HMAC). Currently, only PBKDF2, HKDF, and scrypt are supported. For example, **PBKDF2\|SHA256**, **HKDF\|SHA256**, and **SCRYPT**. | 6421 6422**Return value** 6423 6424| Type | Description | 6425| ------------ | ------------------------------------------ | 6426| [Kdf](#kdf11) | Key derivation function instance created.| 6427 6428**Error codes** 6429For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 6430 6431| ID| Error Message | 6432| -------- | ---------------------- | 6433| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 6434| 801 | this operation is not supported. | 6435| 17620001 | memory error. | 6436 6437**Example** 6438- PBKDF2 6439```ts 6440import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 6441 6442let kdf = cryptoFramework.createKdf('PBKDF2|SHA256'); 6443``` 6444 6445## Kdf<sup>11+</sup> 6446 6447Defines the key derivation function class. Before using APIs of this class, you need to create an instance of this class by using **createKdf(algName: string): Kdf**. 6448 6449### Attributes 6450 6451**Atomic service API**: This API can be used in atomic services since API version 12. 6452 6453**System capability**: SystemCapability.Security.CryptoFramework.Kdf 6454 6455The supported system capability is SystemCapability.Security.CryptoFramework in API version 11 and SystemCapability.Security.CryptoFramework.Kdf since API version 12. 6456 6457| Name | Type | Readable| Writable| Description | 6458| ------- | ------ | ---- | ---- | ---------------------------- | 6459| algName | string | Yes | No | Algorithm of the key derivation function.| 6460 6461### generateSecret 6462 6463generateSecret(params: KdfSpec, callback: AsyncCallback\<DataBlob>): void 6464 6465Generates a key based on the specified key derivation parameters. This API uses an asynchronous callback to return the result. 6466 6467**Atomic service API**: This API can be used in atomic services since API version 12. 6468 6469**System capability**: SystemCapability.Security.CryptoFramework.Kdf 6470 6471The supported system capability is SystemCapability.Security.CryptoFramework in API versions 9 to 11 and SystemCapability.Security.CryptoFramework.Kdf since API version 12. 6472 6473**Parameters** 6474 6475| Name | Type | Mandatory| Description | 6476| -------- | ------------------------ | ---- | ---------------------- | 6477| params | [KdfSpec](#kdfspec11) | Yes | Parameters of the key derivation function.| 6478| callback | AsyncCallback\<[DataBlob](#datablob)> | Yes | Callback invoked to return the derived key generated.| 6479 6480**Error codes** 6481For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 6482 6483| ID| Error Message | 6484| -------- | ---------------------- | 6485| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 6486| 17620001 | memory error. | 6487| 17630001 | crypto operation error. | 6488 6489**Example** 6490 6491- PBKDF2 6492 ```ts 6493 import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 6494 6495 let spec: cryptoFramework.PBKDF2Spec = { 6496 algName: 'PBKDF2', 6497 password: '123456', 6498 salt: new Uint8Array(16), 6499 iterations: 10000, 6500 keySize: 32 6501 }; 6502 let kdf = cryptoFramework.createKdf('PBKDF2|SHA256'); 6503 kdf.generateSecret(spec, (err, secret) => { 6504 if (err) { 6505 console.error("key derivation error."); 6506 return; 6507 } 6508 console.info('key derivation output is ' + secret.data); 6509 }); 6510 ``` 6511 6512- HKDF 6513 ```ts 6514 import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 6515 6516 let spec: cryptoFramework.HKDFSpec = { 6517 algName: 'HKDF', 6518 key: '123456', 6519 salt: new Uint8Array(16), 6520 info: new Uint8Array(16), 6521 keySize: 32 6522 }; 6523 let kdf = cryptoFramework.createKdf('HKDF|SHA256|EXTRACT_AND_EXPAND'); 6524 kdf.generateSecret(spec, (err, secret) => { 6525 if (err) { 6526 console.error("key derivation error."); 6527 return; 6528 } 6529 console.info('key derivation output is ' + secret.data); 6530 }); 6531 ``` 6532 6533### generateSecret 6534 6535generateSecret(params: KdfSpec): Promise\<DataBlob> 6536 6537Generates a key based on the specified key derivation parameters. This API uses a promise to return the result. 6538 6539**Atomic service API**: This API can be used in atomic services since API version 12. 6540 6541**System capability**: SystemCapability.Security.CryptoFramework.Kdf 6542 6543The supported system capability is SystemCapability.Security.CryptoFramework in API versions 9 to 11 and SystemCapability.Security.CryptoFramework.Kdf since API version 12. 6544 6545**Parameters** 6546 6547| Name| Type | Mandatory| Description | 6548| ------ | ------ | ---- | ---------------------- | 6549| params | [KdfSpec](#kdfspec11) | Yes | Parameters of the key derivation function.| 6550 6551**Return value** 6552 6553| Type | Description | 6554| ------------------ | -------- | 6555| Promise\<[DataBlob](#datablob)> | Promise used to return the derived key generated.| 6556 6557**Error codes** 6558For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 6559 6560| ID| Error Message | 6561| -------- | ---------------------- | 6562| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 6563| 17620001 | memory error. | 6564| 17630001 | crypto operation error. | 6565 6566**Example** 6567 6568- PBKDF2 6569 ```ts 6570 import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 6571 import { BusinessError } from '@kit.BasicServicesKit'; 6572 6573 let spec: cryptoFramework.PBKDF2Spec = { 6574 algName: 'PBKDF2', 6575 password: '123456', 6576 salt: new Uint8Array(16), 6577 iterations: 10000, 6578 keySize: 32 6579 }; 6580 let kdf = cryptoFramework.createKdf('PBKDF2|SHA256'); 6581 let kdfPromise = kdf.generateSecret(spec); 6582 kdfPromise.then(secret => { 6583 console.info('key derivation output is ' + secret.data); 6584 }).catch((error: BusinessError) => { 6585 console.error("key derivation error, " + error.message); 6586 }); 6587 ``` 6588 6589- HKDF 6590 ```ts 6591 import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 6592 import { BusinessError } from '@kit.BasicServicesKit'; 6593 6594 let spec: cryptoFramework.HKDFSpec = { 6595 algName: 'HKDF', 6596 key: '123456', 6597 salt: new Uint8Array(16), 6598 info: new Uint8Array(16), 6599 keySize: 32 6600 }; 6601 let kdf = cryptoFramework.createKdf('HKDF|SHA256|EXTRACT_AND_EXPAND'); 6602 let kdfPromise = kdf.generateSecret(spec); 6603 kdfPromise.then(secret => { 6604 console.info('key derivation output is ' + secret.data); 6605 }).catch((error: BusinessError) => { 6606 console.error("key derivation error, " + error.message); 6607 }); 6608 ``` 6609 6610### generateSecretSync<sup>12+</sup> 6611 6612generateSecretSync(params: KdfSpec): DataBlob 6613 6614Generates a key based on the specified key derivation parameters. This API returns the result synchronously. 6615 6616**Atomic service API**: This API can be used in atomic services since API version 12. 6617 6618**System capability**: SystemCapability.Security.CryptoFramework.Kdf 6619 6620**Parameters** 6621 6622| Name| Type | Mandatory| Description | 6623| ------ | ------ | ---- | ---------------------- | 6624| params | [KdfSpec](#kdfspec11) | Yes | Parameters of the key derivation function.| 6625 6626**Return value** 6627 6628| Type | Description | 6629| ------------------ | -------- | 6630| [DataBlob](#datablob) | Key derived.| 6631 6632**Error codes** 6633For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 6634 6635| ID| Error Message | 6636| -------- | ---------------------- | 6637| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed. | 6638| 17620001 | memory error. | 6639| 17620002 | runtime error. | 6640| 17630001 | crypto operation error. | 6641 6642**Example** 6643 6644- PBKDF2 6645 ```ts 6646 import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 6647 6648 let spec: cryptoFramework.PBKDF2Spec = { 6649 algName: 'PBKDF2', 6650 password: '123456', 6651 salt: new Uint8Array(16), 6652 iterations: 10000, 6653 keySize: 32 6654 }; 6655 let kdf = cryptoFramework.createKdf('PBKDF2|SHA256'); 6656 let secret = kdf.generateSecretSync(spec); 6657 console.info("[Sync]key derivation output is " + secret.data); 6658 ``` 6659 6660- HKDF 6661 ```ts 6662 import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 6663 6664 let spec: cryptoFramework.HKDFSpec = { 6665 algName: 'HKDF', 6666 key: '123456', 6667 salt: new Uint8Array(16), 6668 info: new Uint8Array(16), 6669 keySize: 32 6670 }; 6671 let kdf = cryptoFramework.createKdf('HKDF|SHA256|EXTRACT_AND_EXPAND'); 6672 let secret = kdf.generateSecretSync(spec); 6673 console.info("[Sync]key derivation output is " + secret.data); 6674 ``` 6675