1# @ohos.security.cryptoFramework (Crypto Framework) 2 3<!--Kit: Crypto Architecture Kit--> 4<!--Subsystem: Security--> 5<!--Owner: @zxz--3--> 6<!--Designer: @lanming--> 7<!--Tester: @PAFT--> 8<!--Adviser: @zengyawen--> 9 10The **cryptoFramework** module provides APIs for cryptographic operations, shielding the underlying hardware and algorithm library. 11 12> **NOTE** 13> 14> - 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. 15 16## Modules to Import 17 18```ts 19import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 20``` 21 22## Result 23 24 Enumerates the operation results. 25 26 **System capability**: SystemCapability.Security.CryptoFramework 27 28| Name | Value | Description | 29| ------------------------------------- | -------- | ---------------------------- | 30| INVALID_PARAMS | 401 | Invalid parameter.<br>**Atomic service API**: This API can be used in atomic services since API version 11. | 31| NOT_SUPPORT | 801 | Unsupported operation.<br>**Atomic service API**: This API can be used in atomic services since API version 12. | 32| ERR_OUT_OF_MEMORY | 17620001 | Memory error.<br>**Atomic service API**: This API can be used in atomic services since API version 11. | 33| ERR_RUNTIME_ERROR | 17620002 | Runtime error.<br>**Atomic service API**: This API can be used in atomic services since API version 12. | 34| ERR_PARAMETER_CHECK_FAILED<sup>20+</sup> | 17620003 | Parameter check fails.<br>**Atomic service API**: This API can be used in atomic services since API version 20. | 35| ERR_CRYPTO_OPERATION | 17630001 | Cryptographic operation error.<br>**Atomic service API**: This API can be used in atomic services since API version 11. | 36 37## DataBlob 38 39Represents data of the Binary Large Object (BLOB) type. 40 41 **Atomic service API**: This API can be used in atomic services since API version 11. 42 43 **System capability**: SystemCapability.Security.CryptoFramework 44 45| Name| Type | Read-Only| Optional| Description | 46| ---- | ---------- | ---- | ---- | ------ | 47| data | Uint8Array | No | No | Binary data array.| 48 49> **NOTE** 50> 51> The Uint8Array typed array represents an array of 8-bit unsigned integers. 52 53## ParamsSpec 54 55Encapsulates the parameters used for encryption or decryption. You need to construct its child class object and pass it to [init()](#init-1) for symmetric encryption or decryption. 56 57It applies to the symmetric block 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-1). 58 59**Atomic service API**: This API can be used in atomic services since API version 12. 60 61**System capability**: SystemCapability.Security.CryptoFramework.Cipher 62 63The system capability is **SystemCapability.Security.CryptoFramework** in API versions 9 to 11, and **SystemCapability.Security.CryptoFramework.Cipher** since API version 12. 64 65| Name | Type | Read-Only| Optional| Description | 66| ------- | ------ | ---- | ---- | ------------------------------------------------------------ | 67| algName | string | No | No | Algorithm for symmetric encryption or decryption. The value can be:<br> - **IvParamsSpec**: applicable to CBC,|CTR,|OFB,|and CFB modes.<br> - **GcmParamsSpec**: applicable to GCM mode.<br> - **CcmParamsSpec**: applicable to CCM mode.| 68 69> **NOTE** 70> 71> The **params** parameter in [init()](#init-1) 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 must set **algName** for its parent class **ParamsSpec** to specify the child class object to be passed to **init()**. 72 73## IvParamsSpec 74 75Encapsulates the parameters for encryption or decryption using a block cipher mode that requires an IV. It is a child class of [ParamsSpec](#paramsspec) and used as a parameter in [init()](#init-1) for symmetric encryption or decryption. 76 77This class is applicable to block cipher modes that require an IV, such as CBC, CTR, OFB, and CFB. 78 79**Atomic service API**: This API can be used in atomic services since API version 12. 80 81**System capability**: SystemCapability.Security.CryptoFramework.Cipher 82 83The system capability is **SystemCapability.Security.CryptoFramework** in API versions 9 to 11, and **SystemCapability.Security.CryptoFramework.Cipher** since API version 12. 84 85| Name| Type | Read-Only| Optional| Description | 86| ---- | --------------------- | ---- | ---- | ------------------------------------------------------------ | 87| iv | [DataBlob](#datablob) | No | No | IV for encryption or decryption. Options:<br>- AES CBC,|CTR,|OFB,|or CFB mode: The IV length is 16 bytes.<br>- 3DES CBC,|OFB,|or CFB mode: The IV length is 8 bytes.<br>- SM4<sup>10+</sup> CBC,|CTR,|OFB,|or CFB mode: The IV length is 16 bytes.| 88 89> **NOTE** 90> 91> Before passing a value to [init()](#init-1), specify **algName** for its parent class [ParamsSpec](#paramsspec). 92 93## GcmParamsSpec 94 95Encapsulates the parameters for encryption or decryption using a block cipher mode that requires an IV. It is a child class of [ParamsSpec](#paramsspec) and used as a parameter in [init()](#init-1) for symmetric encryption or decryption. 96 97**GcmParamsSpec** applies to GCM mode. 98 99**Atomic service API**: This API can be used in atomic services since API version 12. 100 101**System capability**: SystemCapability.Security.CryptoFramework.Cipher 102 103The system capability is **SystemCapability.Security.CryptoFramework** in API versions 9 to 11, and **SystemCapability.Security.CryptoFramework.Cipher** since API version 12. 104 105| Name | Type | Read-Only| Optional| Description | 106| ------- | --------------------- | ---- | ---- | ------------------------------------------------------------ | 107| iv | [DataBlob](#datablob) | No | No | IV, which is of 1 to 16 bytes. A 12-byte IV is commonly used. | 108| aad | [DataBlob](#datablob) | No | No | Additional authentication data (AAD), which is of 0 to INT_MAX bytes. A 16-byte AAD is commonly used. | 109| authTag | [DataBlob](#datablob) | No | No | Authentication tag, which is of 16 bytes.<br>When GCM mode is used for encryption, you need to extract the last 16 bytes from the [DataBlob](#datablob) returned by [doFinal()](#dofinal) or [doFinalSync()](#dofinalsync12) and use them as **authTag** in **GcmParamsSpec** for [init()](#init-1) or [initSync()](#initsync12).| 110 111> **NOTE** 112> 113> 1. Before passing a value to [init()](#init-1), specify **algName** for its parent class [ParamsSpec](#paramsspec). 114> 2. The Crypto framework imposes no additional restrictions on the IV of 1 to 16 bytes. However, the operation result depends on the underlying OpenSSL support. 115> 3. If **aad** is not required or the **aad** length is 0, you can set its **data** attribute to an empty Uint8Array in the **aad: { data: new Uint8Array() }** format when constructing **GcmParamsSpec**. 116 117## CcmParamsSpec 118 119Encapsulates the parameters for encryption or decryption using a block cipher mode that requires an IV. It is a child class of [ParamsSpec](#paramsspec) and used as a parameter in [init()](#init-1) for symmetric encryption or decryption. 120 121**CcmParamsSpec** applies to CCM mode. 122 123**Atomic service API**: This API can be used in atomic services since API version 12. 124 125**System capability**: SystemCapability.Security.CryptoFramework.Cipher 126 127The system capability is **SystemCapability.Security.CryptoFramework** in API versions 9 to 11, and **SystemCapability.Security.CryptoFramework.Cipher** since API version 12. 128 129| Name | Type | Read-Only| Optional| Description | 130| ------- | --------------------- | ---- | ---- | ------------------------------------------------------------ | 131| iv | [DataBlob](#datablob) | No | No | IV, which is of 7 bytes. | 132| aad | [DataBlob](#datablob) | No | No | AAD, which is of 8 bytes. | 133| authTag | [DataBlob](#datablob) | No | No | Authentication tag, which is of 12 bytes.<br>When CCM mode is used for encryption, you need to extract the last 12 bytes from the [DataBlob](#datablob) returned by [doFinal()](#dofinal) or [doFinalSync()](#dofinalsync12) and use them as **authTag** in [CcmParamsSpec](#ccmparamsspec) for [init()](#init-1) or [initSync()](#initsync12).| 134 135> **NOTE** 136> 137> Before passing a value to [init()](#init-1), specify **algName** for its parent class [ParamsSpec](#paramsspec). 138 139## CryptoMode 140 141Enumerates the cryptographic operations. 142 143**Atomic service API**: This API can be used in atomic services since API version 12. 144 145**System capability**: SystemCapability.Security.CryptoFramework.Cipher 146 147The system capability is **SystemCapability.Security.CryptoFramework** in API versions 9 to 11, and **SystemCapability.Security.CryptoFramework.Cipher** since API version 12. 148 149| Name | Value | Description | 150| ------------ | ---- | ------------------ | 151| ENCRYPT_MODE | 0 | Encryption.| 152| DECRYPT_MODE | 1 | Decryption.| 153 154## AsyKeySpecItem<sup>10+</sup> 155 156Enumerates the asymmetric key parameters. 157 158**Atomic service API**: This API can be used in atomic services since API version 12. 159 160**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 161 162The system capability is **SystemCapability.Security.CryptoFramework** in API versions 10 to 11, and **SystemCapability.Security.CryptoFramework.Key.AsymKey** since API version 12. 163 164| Name | Value | Description | 165| ------------ | ---- | ---------------- | 166| DSA_P_BN | 101 | Prime modulus **p** in the DSA algorithm.| 167| DSA_Q_BN | 102 | Parameter **q**, prime factor of (p – 1) in the DSA algorithm.| 168| DSA_G_BN | 103 | Parameter **g** in the DSA algorithm.| 169| DSA_SK_BN | 104 | Private key **sk** in the DSA algorithm.| 170| DSA_PK_BN | 105 | Public key **pk** in the DSA algorithm.| 171| ECC_FP_P_BN | 201 | Prime number **p** in the **Fp** field of the elliptic curve in the ECC algorithm.| 172| ECC_A_BN | 202 | First coefficient **a** of the elliptic curve in the ECC algorithm.| 173| ECC_B_BN | 203 | Second coefficient **b** of the elliptic curve in the ECC algorithm.| 174| ECC_G_X_BN | 204 | X coordinate of the base point **g** in the ECC algorithm.| 175| ECC_G_Y_BN | 205 | Y coordinate of the base point **g** in the ECC algorithm.| 176| ECC_N_BN | 206 | Order **n** of the base point **g** in the ECC algorithm.| 177| ECC_H_NUM | 207 | Cofactor **h** in the ECC algorithm.| 178| ECC_SK_BN | 208 | Private key **sk** in the ECC algorithm.| 179| ECC_PK_X_BN | 209 | X coordinate of the public key **pk** (a point on the elliptic curve) in the ECC algorithm.| 180| ECC_PK_Y_BN | 210 | Y coordinate of the public key **pk** (a point on the elliptic curve) in the ECC algorithm.| 181| ECC_FIELD_TYPE_STR | 211 | Elliptic curve field type in the ECC algorithm. Currently, only the **Fp** field is supported.| 182| 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.| 183| ECC_CURVE_NAME_STR | 213 | Standards for Efficient Cryptography Group (SECG) curve name in the ECC algorithm.| 184| RSA_N_BN | 301 | Modulus **n** in the RSA algorithm.| 185| RSA_SK_BN | 302 | Private key **sk** (private key exponent **d**) in the RSA algorithm.| 186| RSA_PK_BN | 303 | Public key **pk** (public key exponent **e**) in the RSA algorithm.| 187| DH_P_BN<sup>11+</sup> | 401 | Prime **p** in the DH algorithm.| 188| DH_G_BN<sup>11+</sup> | 402 | Parameter **g** in the DH algorithm.| 189| DH_L_NUM<sup>11+</sup> | 403 | Length of the private key in the DH algorithm, in bits.| 190| DH_SK_BN<sup>11+</sup> | 404 | Private key **sk** in the DH algorithm.| 191| DH_PK_BN<sup>11+</sup> | 405 | Public key **pk** in the DH algorithm.| 192| ED25519_SK_BN<sup>11+</sup> | 501 | Private key **sk** in the Ed25519 algorithm.| 193| ED25519_PK_BN<sup>11+</sup> | 502 | Public key **pk** in the Ed25519 algorithm.| 194| X25519_SK_BN<sup>11+</sup> | 601 | Private key **sk** in the X25519 algorithm.| 195| X25519_PK_BN<sup>11+</sup> | 602 | Public key **pk** in the X25519 algorithm.| 196 197## AsyKeySpecType<sup>10+</sup> 198 199Enumerates the key parameter types. 200 201**Atomic service API**: This API can be used in atomic services since API version 12. 202 203**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 204 205The system capability is **SystemCapability.Security.CryptoFramework** in API versions 10 to 11, and **SystemCapability.Security.CryptoFramework.Key.AsymKey** since API version 12. 206 207| Name | Value | Description | 208| ------------ | ---- | ---------------- | 209| COMMON_PARAMS_SPEC | 0 | Common parameter of the public and private keys. You can use [generateKeyPair](#generatekeypair10) to randomly generate a key pair based on the parameters of this type.| 210| PRIVATE_KEY_SPEC | 1 | Parameter of the private key. You can use [generatePriKey](#generateprikey10) to generate a private key based on the parameters of this type.| 211| PUBLIC_KEY_SPEC | 2 | Parameter of the public key. You can use [generatePubKey](#generatepubkey10) to generate a public key based on the parameters of this type.| 212| KEY_PAIR_SPEC | 3 | Full parameters of the public and private keys. You can use [generateKeyPair](#generatekeypair10) to generate a key pair based on the parameters of this type.| 213 214## CipherSpecItem<sup>10+</sup> 215 216Enumerates encryption and decryption parameters, which can be set by using [setCipherSpec](#setcipherspec10) and obtained by using [getCipherSpec](#getcipherspec10). 217 218Currently, 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). 219 220**Atomic service API**: This API can be used in atomic services since API version 12. 221 222**System capability**: SystemCapability.Security.CryptoFramework.Cipher 223 224The system capability is **SystemCapability.Security.CryptoFramework** in API versions 10 to 11, and **SystemCapability.Security.CryptoFramework.Cipher** since API version 12. 225 226| Name | Value | Description | 227| ------------ | ---- | ---------------- | 228| OAEP_MD_NAME_STR | 100 | Message digest (MD) algorithm used with the PKCS1_OAEP padding mode in RSA.| 229| OAEP_MGF_NAME_STR | 101 | Mask generation algorithm used with the PKCS1_OAEP padding mode in RSA. Currently, only MGF1 is supported.| 230| OAEP_MGF1_MD_STR | 102 | MD algorithm for the MGF1 mask generation used with the PKCS1_OAEP padding mode in RSA.| 231| OAEP_MGF1_PSRC_UINT8ARR | 103 | **pSource** byte stream used with the PKCS1_OAEP padding mode in RSA.| 232| SM2_MD_NAME_STR<sup>11+</sup> | 104 | MD algorithm used in SM2.| 233 234## SignSpecItem<sup>10+</sup> 235 236Enumerates the signing and signature verification parameters, which can be set by using [setSignSpec](#setsignspec10) and [setVerifySpec](#setverifyspec10), and obtained by using [getSignSpec](#getsignspec10) and [getVerifySpec](#getverifyspec10). 237 238Currently, 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). 239 240**Atomic service API**: This API can be used in atomic services since API version 12. 241 242**System capability**: SystemCapability.Security.CryptoFramework.Signature 243 244The system capability is **SystemCapability.Security.CryptoFramework** in API versions 10 to 11, and **SystemCapability.Security.CryptoFramework.Signature** since API version 12. 245 246| Name | Value | Description | 247| ------------ | ---- | ---------------- | 248| PSS_MD_NAME_STR | 100 | MD algorithm used with the PSS padding mode in RSA.| 249| PSS_MGF_NAME_STR | 101 | Mask generation algorithm used with the PSS padding mode in RSA. Currently, only MGF1 is supported.| 250| PSS_MGF1_MD_STR | 102 | MD parameters for the MGF1 mask generation used with the PSS padding mode in RSA.| 251| PSS_SALT_LEN_NUM | 103 | Length of the salt in bytes used with the PSS padding mode in RSA.| 252| PSS_TRAILER_FIELD_NUM | 104 | Trailer field used in the encoding operation when PSS padding mode is used in RSA.| 253| SM2_USER_ID_UINT8ARR<sup>11+</sup> | 105 | User ID field in SM2.| 254 255## AsyKeySpec<sup>10+</sup> 256 257Defines 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. 258 259**Atomic service API**: This API can be used in atomic services since API version 12. 260 261**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 262 263The system capability is **SystemCapability.Security.CryptoFramework** in API versions 10 to 11, and **SystemCapability.Security.CryptoFramework.Key.AsymKey** since API version 12. 264 265| Name | Type | Read-Only| Optional| Description | 266| ------- | ------ | ---- | ---- | ------------------------------------------------------------ | 267| algName | string | No | No | Asymmetric key algorithm, for example, **RSA**, **DSA**, **ECC**, **SM2**, **Ed25519**, **X25519**, or **DH**.| 268| specType | [AsyKeySpecType](#asykeyspectype10) | No | No| Key parameter type, which is used to distinguish public and private key parameters.| 269 270## DSACommonParamsSpec<sup>10+</sup> 271 272Defines 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. 273 274To generate a key based on key parameters, pass it to [createAsyKeyGeneratorBySpec()](#cryptoframeworkcreateasykeygeneratorbyspec10) to create a key generator. 275 276**Atomic service API**: This API can be used in atomic services since API version 12. 277 278**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 279 280The system capability is **SystemCapability.Security.CryptoFramework** in API versions 10 to 11, and **SystemCapability.Security.CryptoFramework.Key.AsymKey** since API version 12. 281 282| Name | Type | Read-Only| Optional| Description | 283| ------- | ------ | ---- | ---- | ------------------------------------------------------------ | 284| p | bigint | No | No | Prime modulus **p** in the DSA algorithm.| 285| q | bigint | No | No | Parameter **q**, prime factor of (**p** – 1) in the DSA algorithm.| 286| g | bigint | No | No | Parameter **g** in the DSA algorithm.| 287 288## DSAPubKeySpec<sup>10+</sup> 289 290Defines a child class of [AsyKeySpec](#asykeyspec10) used to specify the parameters of the public key in the DSA algorithm. 291 292To generate a key based on key parameters, pass it to [createAsyKeyGeneratorBySpec()](#cryptoframeworkcreateasykeygeneratorbyspec10) to create a key generator. 293 294**Atomic service API**: This API can be used in atomic services since API version 12. 295 296**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 297 298The system capability is **SystemCapability.Security.CryptoFramework** in API versions 10 to 11, and **SystemCapability.Security.CryptoFramework.Key.AsymKey** since API version 12. 299 300| Name | Type | Read-Only| Optional| Description | 301| ------- | ------ | ---- | ---- | ------------------------------------------------------------ | 302| params | [DSACommonParamsSpec](#dsacommonparamsspec10) | No | No | Common parameters of the public and private keys in the DSA algorithm.| 303| pk | bigint | No | No | Public key in the DSA algorithm.| 304 305## DSAKeyPairSpec<sup>10+</sup> 306 307Defines a child class of [AsyKeySpec](#asykeyspec10) used to specify full parameters of the public and private keys in the DSA algorithm. 308 309To generate a key based on key parameters, pass it to [createAsyKeyGeneratorBySpec()](#cryptoframeworkcreateasykeygeneratorbyspec10) to create a key generator. 310 311**Atomic service API**: This API can be used in atomic services since API version 12. 312 313**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 314 315The system capability is **SystemCapability.Security.CryptoFramework** in API versions 10 to 11, and **SystemCapability.Security.CryptoFramework.Key.AsymKey** since API version 12. 316 317| Name | Type | Read-Only| Optional| Description | 318| ------- | ------ | ---- | ---- | ------------------------------------------------------------ | 319| params | [DSACommonParamsSpec](#dsacommonparamsspec10) | No | No | Common parameters of the public and private keys in the DSA algorithm.| 320| sk | bigint | No | No | Private key **sk** in the DSA algorithm.| 321| pk | bigint | No | No | Public key in the DSA algorithm.| 322 323## ECField<sup>10+</sup> 324 325Defines the field type of an elliptic curve. Currently, only the **Fp** field is supported. 326 327**Atomic service API**: This API can be used in atomic services since API version 12. 328 329**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 330 331The system capability is **SystemCapability.Security.CryptoFramework** in API versions 10 to 11, and **SystemCapability.Security.CryptoFramework.Key.AsymKey** since API version 12. 332 333| Name | Type | Read-Only| Optional| Description | 334| ------- | ------ | ---- | ---- | ------------------------------------------------------------ | 335| fieldType | string | No | No | Type of the elliptic curve field. Currently, only **Fp** is supported.| 336 337## ECFieldFp<sup>10+</sup> 338 339Defines the prime field of the elliptic curve. It is a child class of [ECField](#ecfield10). 340 341**Atomic service API**: This API can be used in atomic services since API version 12. 342 343**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 344 345The system capability is **SystemCapability.Security.CryptoFramework** in API versions 10 to 11, and **SystemCapability.Security.CryptoFramework.Key.AsymKey** since API version 12. 346 347| Name | Type | Read-Only| Optional| Description | 348| ------- | ------ | ---- | ---- | ------------------------------------------------------------ | 349| p | bigint | No | No | Value of the prime number **p**.| 350 351## Point<sup>10+</sup> 352 353Defines a point on the elliptic curve. 354 355**Atomic service API**: This API can be used in atomic services since API version 12. 356 357**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 358 359The system capability is **SystemCapability.Security.CryptoFramework** in API versions 10 to 11, and **SystemCapability.Security.CryptoFramework.Key.AsymKey** since API version 12. 360 361| Name | Type | Read-Only| Optional| Description | 362| ------- | ------ | ---- | ---- | ------------------------------------------------------------ | 363| x | bigint | No | No | X coordinate of the point on an elliptic curve.| 364| y | bigint | No | No | Y coordinate of the point on an elliptic curve.| 365 366## ECCCommonParamsSpec<sup>10+</sup> 367 368Defines 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. 369 370To generate a key based on key parameters, pass it to [createAsyKeyGeneratorBySpec()](#cryptoframeworkcreateasykeygeneratorbyspec10) to create a key generator. 371 372**Atomic service API**: This API can be used in atomic services since API version 12. 373 374**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 375 376The system capability is **SystemCapability.Security.CryptoFramework** in API versions 10 to 11, and **SystemCapability.Security.CryptoFramework.Key.AsymKey** since API version 12. 377 378| Name | Type | Read-Only| Optional| Description | 379| ------- | ------ | ---- | ---- | ------------------------------------------------------------ | 380| field | [ECField](#ecfield10) | No | No | Field of the elliptic curve. Currently, only **Fp** is supported.| 381| a | bigint | No | No | First coefficient **a** of the elliptic curve.| 382| b | bigint | No | No | Second coefficient **b** of the elliptic curve.| 383| g | [Point](#point10) | No | No | Base point g.| 384| n | bigint | No | No | Order **n** of the base point **g**.| 385| h | number | No | No | Cofactor **h**.| 386 387## ECCPriKeySpec<sup>10+</sup> 388 389Defines a child class of [AsyKeySpec](#asykeyspec10) used to specify the parameters of the private key in the ECC algorithm. 390 391To generate a key based on key parameters, pass it to [createAsyKeyGeneratorBySpec()](#cryptoframeworkcreateasykeygeneratorbyspec10) to create a key generator. 392 393**Atomic service API**: This API can be used in atomic services since API version 12. 394 395**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 396 397The system capability is **SystemCapability.Security.CryptoFramework** in API versions 10 to 11, and **SystemCapability.Security.CryptoFramework.Key.AsymKey** since API version 12. 398 399| Name | Type | Read-Only| Optional| Description | 400| ------- | ------ | ---- | ---- | ------------------------------------------------------------ | 401| params | [ECCCommonParamsSpec](#ecccommonparamsspec10) | No | No | Common parameters of the public and private keys in the ECC algorithm.| 402| sk | bigint | No | No | Private key **sk** in the ECC algorithm.| 403 404## ECCPubKeySpec<sup>10+</sup> 405 406Defines a child class of [AsyKeySpec](#asykeyspec10) used to specify the parameters of the public key in the ECC algorithm. 407 408To generate a key based on key parameters, pass it to [createAsyKeyGeneratorBySpec()](#cryptoframeworkcreateasykeygeneratorbyspec10) to create a key generator. 409 410**Atomic service API**: This API can be used in atomic services since API version 12. 411 412**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 413 414The system capability is **SystemCapability.Security.CryptoFramework** in API versions 10 to 11, and **SystemCapability.Security.CryptoFramework.Key.AsymKey** since API version 12. 415 416| Name | Type | Read-Only| Optional| Description | 417| ------- | ------ | ---- | ---- | ------------------------------------------------------------ | 418| params | [ECCCommonParamsSpec](#ecccommonparamsspec10) | No | No | Common parameters of the public and private keys in the ECC algorithm.| 419| pk | [Point](#point10) | No | No | Public key **pk** in the ECC algorithm.| 420 421## ECCKeyPairSpec<sup>10+</sup> 422 423Defines a child class of [AsyKeySpec](#asykeyspec10) used to specify full parameters of the public and private keys in the ECC algorithm. 424 425To generate a key based on key parameters, pass it to [createAsyKeyGeneratorBySpec()](#cryptoframeworkcreateasykeygeneratorbyspec10) to create a key generator. 426 427**Atomic service API**: This API can be used in atomic services since API version 12. 428 429**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 430 431The system capability is **SystemCapability.Security.CryptoFramework** in API versions 10 to 11, and **SystemCapability.Security.CryptoFramework.Key.AsymKey** since API version 12. 432 433| Name | Type | Read-Only| Optional| Description | 434| ------- | ------ | ---- | ---- | ------------------------------------------------------------ | 435| params | [ECCCommonParamsSpec](#ecccommonparamsspec10) | No | No | Common parameters of the public and private keys in the ECC algorithm.| 436| sk | bigint | No | No | Private key **sk** in the ECC algorithm.| 437| pk | [Point](#point10) | No | No | Public key **pk** in the ECC algorithm.| 438 439## RSACommonParamsSpec<sup>10+</sup> 440 441Defines 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. 442 443To generate a key based on key parameters, pass it to [createAsyKeyGeneratorBySpec()](#cryptoframeworkcreateasykeygeneratorbyspec10) to create a key generator. 444 445**Atomic service API**: This API can be used in atomic services since API version 12. 446 447**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 448 449The system capability is **SystemCapability.Security.CryptoFramework** in API versions 10 to 11, and **SystemCapability.Security.CryptoFramework.Key.AsymKey** since API version 12. 450 451| Name | Type | Read-Only| Optional| Description | 452| ------- | ------ | ---- | ---- | ------------------------------------------------------------ | 453| n | bigint | No | No | Modulus **n**.| 454 455## RSAPubKeySpec<sup>10+</sup> 456 457Defines a child class of [AsyKeySpec](#asykeyspec10) used to specify the parameters of the public key in the RSA algorithm. 458 459To generate a key based on key parameters, pass it to [createAsyKeyGeneratorBySpec()](#cryptoframeworkcreateasykeygeneratorbyspec10) to create a key generator. 460 461**Atomic service API**: This API can be used in atomic services since API version 12. 462 463**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 464 465The system capability is **SystemCapability.Security.CryptoFramework** in API versions 10 to 11, and **SystemCapability.Security.CryptoFramework.Key.AsymKey** since API version 12. 466 467| Name | Type | Read-Only| Optional| Description | 468| ------- | ------ | ---- | ---- | ------------------------------------------------------------ | 469| params | [RSACommonParamsSpec](#rsacommonparamsspec10) | No | No | Common parameters of the public and private keys in the RSA algorithm.| 470| pk | bigint | No | No | Public key **pk** in the RSA algorithm.| 471 472## RSAKeyPairSpec<sup>10+</sup> 473 474Defines a child class of [AsyKeySpec](#asykeyspec10) used to specify full parameters of the public and private keys in the RSA algorithm. 475 476To generate a key based on key parameters, pass it to [createAsyKeyGeneratorBySpec()](#cryptoframeworkcreateasykeygeneratorbyspec10) to create a key generator. 477 478**Atomic service API**: This API can be used in atomic services since API version 12. 479 480**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 481 482The system capability is **SystemCapability.Security.CryptoFramework** in API versions 10 to 11, and **SystemCapability.Security.CryptoFramework.Key.AsymKey** since API version 12. 483 484| Name | Type | Read-Only| Optional| Description | 485| ------- | ------ | ---- | ---- | ------------------------------------------------------------ | 486| params | [RSACommonParamsSpec](#rsacommonparamsspec10) | No | No | Common parameters of the public and private keys in the RSA algorithm.| 487| sk | bigint | No | No | Private key **sk** in the RSA algorithm.| 488| pk | bigint | No | No | Public key **pk** in the RSA algorithm.| 489 490## ED25519PriKeySpec<sup>11+</sup> 491 492Defines a child class of [AsyKeySpec](#asykeyspec10) used to specify the parameters of the private key in the Ed25519 algorithm. 493 494To generate a key based on key parameters, pass it to [createAsyKeyGeneratorBySpec()](#cryptoframeworkcreateasykeygeneratorbyspec10) to create a key generator. 495 496**Atomic service API**: This API can be used in atomic services since API version 12. 497 498**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 499 500The system capability is **SystemCapability.Security.CryptoFramework** in API version 11, and **SystemCapability.Security.CryptoFramework.Key.AsymKey** since API version 12. 501 502| Name| Type | Read-Only| Optional| Description | 503| ---- | ------ | ---- | ---- | ------------------------- | 504| sk | bigint | No | No | Private key **sk** in the Ed25519 algorithm.| 505 506## ED25519PubKeySpec<sup>11+</sup> 507 508Defines a child class of [AsyKeySpec](#asykeyspec10) used to specify the parameters of the public key in the Ed25519 algorithm. 509 510To generate a key based on key parameters, pass it to [createAsyKeyGeneratorBySpec()](#cryptoframeworkcreateasykeygeneratorbyspec10) to create a key generator. 511 512**Atomic service API**: This API can be used in atomic services since API version 12. 513 514**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 515 516The system capability is **SystemCapability.Security.CryptoFramework** in API version 11, and **SystemCapability.Security.CryptoFramework.Key.AsymKey** since API version 12. 517 518| Name| Type | Read-Only| Optional| Description | 519| ---- | ------ | ---- | ---- | ------------------------- | 520| pk | bigint | No | No | Public key **pk** in the Ed25519 algorithm.| 521 522## ED25519KeyPairSpec<sup>11+</sup> 523 524Defines a child class of [AsyKeySpec](#asykeyspec10) used to specify full parameters of the public and private keys in the Ed25519 algorithm. 525 526To generate a key based on key parameters, pass it to [createAsyKeyGeneratorBySpec()](#cryptoframeworkcreateasykeygeneratorbyspec10) to create a key generator. 527 528**Atomic service API**: This API can be used in atomic services since API version 12. 529 530**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 531 532The system capability is **SystemCapability.Security.CryptoFramework** in API version 11, and **SystemCapability.Security.CryptoFramework.Key.AsymKey** since API version 12. 533 534| Name| Type | Read-Only| Optional| Description | 535| ---- | ------ | ---- | ---- | ------------------------- | 536| sk | bigint | No | No | Private key **sk** in the Ed25519 algorithm.| 537| pk | bigint | No | No | Public key **pk** in the Ed25519 algorithm.| 538 539## X25519PriKeySpec<sup>11+</sup> 540 541Defines a child class of [AsyKeySpec](#asykeyspec10) used to specify the parameters of the private key in the X25519 algorithm. 542 543To generate a key based on key parameters, pass it to [createAsyKeyGeneratorBySpec()](#cryptoframeworkcreateasykeygeneratorbyspec10) to create a key generator. 544 545**Atomic service API**: This API can be used in atomic services since API version 12. 546 547**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 548 549The system capability is **SystemCapability.Security.CryptoFramework** in API version 11, and **SystemCapability.Security.CryptoFramework.Key.AsymKey** since API version 12. 550 551| Name| Type | Read-Only| Optional| Description | 552| ---- | ------ | ---- | ---- | ------------------------ | 553| sk | bigint | No | No | Private key **sk** in the X25519 algorithm.| 554 555## X25519PubKeySpec<sup>11+</sup> 556 557Defines a child class of [AsyKeySpec](#asykeyspec10) used to specify the parameters of the public key in the X25519 algorithm. 558 559To generate a key based on key parameters, pass it to [createAsyKeyGeneratorBySpec()](#cryptoframeworkcreateasykeygeneratorbyspec10) to create a key generator. 560 561**Atomic service API**: This API can be used in atomic services since API version 12. 562 563**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 564 565The system capability is **SystemCapability.Security.CryptoFramework** in API version 11, and **SystemCapability.Security.CryptoFramework.Key.AsymKey** since API version 12. 566 567| Name| Type | Read-Only| Optional| Description | 568| ---- | ------ | ---- | ---- | ------------------------ | 569| pk | bigint | No | No | Public key **pk** in the X25519 algorithm.| 570 571## X25519KeyPairSpec<sup>11+</sup> 572 573Defines a child class of [AsyKeySpec](#asykeyspec10) used to specify full parameters of the public and private keys in the X25519 algorithm. 574 575To generate a key based on key parameters, pass it to [createAsyKeyGeneratorBySpec()](#cryptoframeworkcreateasykeygeneratorbyspec10) to create a key generator. 576 577**Atomic service API**: This API can be used in atomic services since API version 12. 578 579**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 580 581The system capability is **SystemCapability.Security.CryptoFramework** in API version 11, and **SystemCapability.Security.CryptoFramework.Key.AsymKey** since API version 12. 582 583| Name| Type | Read-Only| Optional| Description | 584| ---- | ------ | ---- | ---- | ------------------------ | 585| sk | bigint | No | No | Private key **sk** in the X25519 algorithm.| 586| pk | bigint | No | No | Public key **pk** in the X25519 algorithm.| 587 588## DHCommonParamsSpec<sup>11+</sup> 589 590Defines a child class of [AsyKeySpec](#asykeyspec10) used to specify the parameters of the public and private keys in the DH algorithm. 591 592To generate a key based on key parameters, pass it to [createAsyKeyGeneratorBySpec()](#cryptoframeworkcreateasykeygeneratorbyspec10) to create a key generator. 593 594**Atomic service API**: This API can be used in atomic services since API version 12. 595 596**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 597 598The system capability is **SystemCapability.Security.CryptoFramework** in API version 11, and **SystemCapability.Security.CryptoFramework.Key.AsymKey** since API version 12. 599 600| Name| Type | Read-Only| Optional| Description | 601| ---- | ------ | ---- | ---- | ----------------------------------- | 602| p | bigint | No | No | Large prime **p** in the DH algorithm. | 603| g | bigint | No | No | Parameter **g** in the DH algorithm. | 604| l | number | No | No | Length of the private key in the DH algorithm, in bits.| 605 606## DHPriKeySpec<sup>11+</sup> 607 608Defines a child class of [AsyKeySpec](#asykeyspec10) used to specify the parameters of the private key in the DH algorithm. 609 610To generate a key based on key parameters, pass it to [createAsyKeyGeneratorBySpec()](#cryptoframeworkcreateasykeygeneratorbyspec10) to create a key generator. 611 612**Atomic service API**: This API can be used in atomic services since API version 12. 613 614**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 615 616The system capability is **SystemCapability.Security.CryptoFramework** in API version 11, and **SystemCapability.Security.CryptoFramework.Key.AsymKey** since API version 12. 617 618| Name | Type | Read-Only| Optional| Description | 619| ------ | ------------------ | ---- | ---- | ------------------------------------ | 620| params | [DHCommonParamsSpec](#dhcommonparamsspec11) | No | No | Common parameters of the public and private keys in the DH algorithm.| 621| sk | bigint | No | No | Private key **sk** in the DH algorithm. | 622 623## DHPubKeySpec<sup>11+</sup> 624 625Defines a child class of [AsyKeySpec](#asykeyspec10) used to specify the parameters of the public key in the DH algorithm. 626 627To generate a key based on key parameters, pass it to [createAsyKeyGeneratorBySpec()](#cryptoframeworkcreateasykeygeneratorbyspec10) to create a key generator. 628 629**Atomic service API**: This API can be used in atomic services since API version 12. 630 631**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 632 633The system capability is **SystemCapability.Security.CryptoFramework** in API version 11, and **SystemCapability.Security.CryptoFramework.Key.AsymKey** since API version 12. 634 635| Name | Type | Read-Only| Optional| Description | 636| ------ | ------------------ | ---- | ---- | ------------------------------------ | 637| params | [DHCommonParamsSpec](#dhcommonparamsspec11) | No | No | Common parameters of the public and private keys in the DH algorithm.| 638| pk | bigint | No | No | Public key **pk** in the DH algorithm. | 639 640## DHKeyPairSpec<sup>11+</sup> 641 642Defines a child class of [AsyKeySpec](#asykeyspec10) used to specify full parameters of the public and private keys in the DH algorithm. 643 644To generate a key based on key parameters, pass it to [createAsyKeyGeneratorBySpec()](#cryptoframeworkcreateasykeygeneratorbyspec10) to create a key generator. 645 646**Atomic service API**: This API can be used in atomic services since API version 12. 647 648**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 649 650The system capability is **SystemCapability.Security.CryptoFramework** in API version 11, and **SystemCapability.Security.CryptoFramework.Key.AsymKey** since API version 12. 651 652| Name | Type | Read-Only| Optional| Description | 653| ------ | ------------------ | ---- | ---- | ------------------------------------ | 654| params | [DHCommonParamsSpec](#dhcommonparamsspec11) | No | No | Common parameters of the public and private keys in the DH algorithm.| 655| sk | bigint | No | No | Private key **sk** in the DH algorithm. | 656| pk | bigint | No | No | Public key **pk** in the DH algorithm. | 657 658## KdfSpec<sup>11+</sup> 659 660Defines 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**. 661 662**Atomic service API**: This API can be used in atomic services since API version 12. 663 664**System capability**: SystemCapability.Security.CryptoFramework.Kdf 665 666The system capability is **SystemCapability.Security.CryptoFramework** in API version 11, and **SystemCapability.Security.CryptoFramework.Kdf** since API version 12. 667 668| Name | Type | Read-Only| Optional| Description | 669| ------- | ------ | ---- | ---- | ------------------------------------------------------------ | 670| algName | string | No | No | Algorithm of the key derivation function, for example, **PBKDF2**.| 671 672## PBKDF2Spec<sup>11+</sup> 673 674Defines the child class of [KdfSpec](#kdfspec11). It is used as a parameter for PBKDF2 key derivation. 675 676**Atomic service API**: This API can be used in atomic services since API version 12. 677 678**System capability**: SystemCapability.Security.CryptoFramework.Kdf 679 680The system capability is **SystemCapability.Security.CryptoFramework** in API version 11, and **SystemCapability.Security.CryptoFramework.Kdf** since API version 12. 681 682| Name | Type | Read-Only| Optional| Description | 683| ------- | ------ | ---- | ---- | ------------------------------------------------------------ | 684| password | string \| Uint8Array | No | No | Original password entered by the user.| 685| salt | Uint8Array | No | No | Salt value.| 686| iterations | number | No | No | Number of iterations. The value must be a positive integer.| 687| keySize | number | No | No | Length of the derived key, in bytes.| 688 689> **NOTE** 690> 691> **password** is the original password. If **password** of the string type is used, pass in the actual data for key derivation, rather than a HexString or Base64-encoded value. In addition, the string must be encoded in UTF-8, as other encodings may alter the derivation outcome. 692 693## HKDFSpec<sup>12+</sup> 694 695Defines the child class of [KdfSpec](#kdfspec11). It is a parameter for HKDF key derivation. 696 697**Atomic service API**: This API can be used in atomic services since API version 12. 698 699**System capability**: SystemCapability.Security.CryptoFramework.Kdf 700 701| Name | Type | Read-Only| Optional| Description | 702| ------- | ------ | ---- | ---- | ------------------------------------------------------------ | 703| key | string \| Uint8Array | No | No | Key material.| 704| salt | Uint8Array | No | No | Salt value.| 705| info | Uint8Array | No | No | Information used to expand the key.| 706| keySize | number | No | No | Length of the derived key, in bytes.| 707 708> **NOTE** 709> 710> **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. 711> 712> 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**. 713> 714> The default mode is **EXTRACT_AND_EXPAND**. The value **HKDF|SHA256|EXTRACT_AND_EXPAND** is equivalent to **HKDF|SHA256**. 715 716## ScryptSpec<sup>18+</sup> 717 718Defines the child class of [KdfSpec](#kdfspec11). It is a parameter for scrypt key derivation function (KDF). 719 720**Atomic service API**: This API can be used in atomic services since API version 18. 721 722**System capability**: SystemCapability.Security.CryptoFramework.Kdf 723 724| Name | Type | Read-Only| Optional| Description | 725| ------- | ------ | ---- | ---- | ------------------------------------------------------------ | 726| passphrase | string \| Uint8Array | No | No | Original password entered by the user.| 727| salt | Uint8Array | No | No | Salt value.| 728| n | number | No | No | Number of iterations. The value must be a positive integer.| 729| p | number | No | No | Parallelization parameter. The value must be a positive integer.| 730| r | number | No | No | Block size. The value must be a positive integer.| 731| maxMemory | number | No | No | Maximum memory size. The value must be a positive integer.| 732| keySize | number | No | No | Length of the derived key, in bytes. The value must be a positive integer.| 733 734> **NOTE** 735> 736> **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. 737 738## SM2CipherTextSpec<sup>12+</sup> 739 740Represents 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. 741 742**Atomic service API**: This API can be used in atomic services since API version 12. 743 744**System capability**: SystemCapability.Security.CryptoFramework.Cipher 745 746| Name | Type | Read-Only| Optional| Description | 747| ------- | ------ | ---- | ---- | ------------------------------------------------------------ | 748| xCoordinate | bigint | No | No | Coordinate X.| 749| yCoordinate | bigint | No | No | Coordinate Y.| 750| cipherTextData | Uint8Array | No | No | Ciphertext.| 751| hashData | Uint8Array | No | No | Hash value.| 752 753> **NOTE** 754> 755> - **hashData** is a value obtained by applying the SM3 algorithm to the plaintext. It has a fixed length of 256 bits. 756> 757> - **cipherTextData** is the ciphertext with the same length as the plaintext. 758> 759> - 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. 760 761## KeyEncodingConfig<sup>18+</sup> 762Represents the RSA private key encoding parameters. You can use it to generate an encoded private key string with the specified algorithm and password. 763 764**Atomic service API**: This API can be used in atomic services since API version 18. 765 766**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 767 768| Name | Type | Read-Only| Optional| Description | 769| ------- | ------ | ---- | ---- | ------------------------------------------------------------ | 770| password | string | No | No | Password used for encoding the private key.| 771| cipherName | string | No | No | Algorithm to use.| 772 773> **NOTE** 774> 775> - **password** specifies the password used for encoding the private key. It is mandatory. 776> 777> - **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. 778 779## MacSpec<sup>18+</sup> 780Represents the message authentication code (MAC) parameters. You need to construct a child class object and use it as a parameter when generating an HMAC or a CMAC. 781 782**Atomic service API**: This API can be used in atomic services since API version 18. 783 784**System capability**: SystemCapability.Security.CryptoFramework.Mac 785 786| Name | Type | Read-Only| Optional| Description | 787| ------- | ------ | ---- | ---- | ------------------------------------------------------------ | 788| algName | string | No | No | Algorithm to use.| 789 790> **NOTE** 791> 792> **algName** specifies the MAC algorithm to use. It is mandatory. 793 794## HmacSpec<sup>18+</sup> 795Represents the child class of [MacSpec](#macspec18). It is used as an input parameter for HMAC generation. 796 797**Atomic service API**: This API can be used in atomic services since API version 18. 798 799**System capability**: SystemCapability.Security.CryptoFramework.Mac 800 801| Name | Type | Read-Only| Optional| Description | 802| ------- | ------ | ---- | ---- | ------------------------------------------------------------ | 803| mdName | string | No | No | MD algorithm to use.| 804 805> **NOTE** 806> 807> **mdName** specifies the HMAC digest algorithm. It is mandatory. 808 809## CmacSpec<sup>18+</sup> 810Represents the child class of [MacSpec](#macspec18). It is used as an input parameter for CMAC generation. 811 812**Atomic service API**: This API can be used in atomic services since API version 18. 813 814**System capability**: SystemCapability.Security.CryptoFramework.Mac 815 816| Name | Type | Read-Only| Optional| Description | 817| ------- | ------ | ---- | ---- | ------------------------------------------------------------ | 818| cipherName | string | No | No | Symmetric encryption algorithm to use.| 819 820> **NOTE** 821> 822> **cipherName** specifies the CMAC symmetric encryption algorithm. It is mandatory. 823 824## EccSignatureSpec<sup>20+</sup> 825 826Represents the SM2 signature data that contains (r, s). 827 828> **NOTE** 829> 830> **r** and **s** are each 256 bits long. 831 832**Atomic service API**: This API can be used in atomic services since API version 20. 833 834**System capability**: SystemCapability.Security.CryptoFramework.Signature 835 836| Name | Type | Read-Only| Optional| Description | 837| ------- | ------ | ---- | ---- | ------------------------------------------------------------ | 838| r | bigint | No | No | Randomized value derived from the elliptic curve calculation using the ephemeral private key during signature generation.| 839| s | bigint | No | No | Signature component, computed using the signer's private key, r, and the hashed message.| 840 841## Key 842 843Provides 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-1) of the [Cipher](#cipher) instance. 844 845Keys can be generated by a key generator. 846 847### Attributes 848 849**Atomic service API**: This API can be used in atomic services since API version 12. 850 851**System capability**: SystemCapability.Security.CryptoFramework.Key 852 853The system capability is **SystemCapability.Security.CryptoFramework** in API versions 9 to 11, and **SystemCapability.Security.CryptoFramework.Key** since API version 12. 854 855| Name | Type | Read-Only| Optional| Description | 856| ------- | ------ | ---- | ---- | ---------------------------- | 857| format | string | Yes | No | Format of the key. | 858| algName | string | Yes | No | Algorithm to use. This parameter contains the key length if the key is a symmetric key.| 859 860### getEncoded 861 862getEncoded(): DataBlob 863 864Obtains 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 comply with the ASN.1 syntax, X.509 specifications, and DER encoding. The private key must comply with the ASN.1 syntax, PKCS #8 specifications, and DER encoding. 865 866> **NOTE** 867> 868> When the RSA algorithm generates a private key using key parameters, **getEncoded** is available for the private key object. 869 870**Atomic service API**: This API can be used in atomic services since API version 12. 871 872**System capability**: SystemCapability.Security.CryptoFramework.Key 873 874The system capability is **SystemCapability.Security.CryptoFramework** in API versions 9 to 11, and **SystemCapability.Security.CryptoFramework.Key** since API version 12. 875 876**Return value** 877 878| Type | Description | 879| --------------------- | ------------------------ | 880| [DataBlob](#datablob) | Key obtained.| 881 882**Error codes** 883For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 884 885| ID| Error Message | 886| -------- | ---------------------- | 887| 801 | this operation is not supported. | 888| 17620001 | memory operation failed. | 889| 17630001 | crypto operation error. | 890 891**Example** 892 893```ts 894import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 895 896async function testGenerateAesKey() { 897 let symKeyGenerator = cryptoFramework.createSymKeyGenerator('AES256'); 898 let symKey = await symKeyGenerator.generateSymKey(); 899 let encodedKey = symKey.getEncoded(); 900 console.info('key hex:' + encodedKey.data); 901} 902``` 903 904## SymKey 905 906Provides APIs for symmetric key operations. It is a child class of [Key](#key). Its objects need to be passed to [init()](#init-1) of the [Cipher](#cipher) instance in symmetric encryption and decryption. 907 908Symmetric keys can be generated by a [SymKeyGenerator](#symkeygenerator). 909 910### clearMem 911 912clearMem(): void 913 914Clears the keys in memory. This API returns the result synchronously. Call this API when the symmetric key instance is no longer required. 915 916**Atomic service API**: This API can be used in atomic services since API version 12. 917 918**System capability**: SystemCapability.Security.CryptoFramework.Key.SymKey 919 920The system capability is **SystemCapability.Security.CryptoFramework** in API versions 9 to 11, and **SystemCapability.Security.CryptoFramework.Key.SymKey** since API version 12. 921 922**Example** 923 924<!--code_no_check--> 925```ts 926let key: cryptoFramework.SymKey; // The key is generated by a symKeyGenerator. The generation process is omitted here. 927let encodedKey = key.getEncoded(); 928console.info('key blob: '+ encodedKey.data); // Display key content. 929key.clearMem(); 930encodedKey = key.getEncoded(); 931console.info('key blob: ' + encodedKey.data); // Display all 0s. 932``` 933 934## PubKey 935 936Provides 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. 937 938The public key can be generated by using the asymmetric key generator [AsyKeyGenerator](#asykeygenerator) or [AsyKeyGeneratorBySpec](#asykeygeneratorbyspec10). 939 940### getAsyKeySpec<sup>10+</sup> 941 942getAsyKeySpec(itemType: AsyKeySpecItem): bigint | string | number 943 944Obtains a key parameter. This API returns the result synchronously. 945 946**Atomic service API**: This API can be used in atomic services since API version 12. 947 948**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 949 950The system capability is **SystemCapability.Security.CryptoFramework** in API versions 10 to 11, and **SystemCapability.Security.CryptoFramework.Key.AsymKey** since API version 12. 951 952**Parameters** 953 954| Name| Type | Mandatory| Description | 955| ---- | --------------------- | ---- | -------------------- | 956| itemType | [AsyKeySpecItem](#asykeyspecitem10) | Yes | Key parameter to obtain.| 957 958**Return value** 959 960| Type | Description | 961| --------------------------- | --------------------------------- | 962| bigint \| string \| number | Content of the key parameter obtained.| 963 964**Error codes** 965For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 966 967| ID| Error Message | 968| -------- | ---------------------- | 969| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 970| 801 | this operation is not supported. | 971| 17620001 | memory operation failed. | 972| 17630001 | crypto operation error. | 973 974**Example** 975 976<!--code_no_check--> 977```ts 978let key: cryptoFramework.PubKey; // key is a public key object. The generation process is omitted here. 979let p = key.getAsyKeySpec(cryptoFramework.AsyKeySpecItem.ECC_FP_P_BN); 980console.info('ecc item --- p: ' + p.toString(16)); 981``` 982 983### getEncodedDer<sup>12+</sup> 984 985getEncodedDer(format: string): DataBlob 986 987Obtains the public key data that complies with the ASN.1 syntax and DER encoding format based on the specified key format (such as the specifications and compression status). Currently, only the ECC compressed and uncompressed public key data is supported. 988 989> **NOTE** 990> 991> The difference between [Key.getEncoded()](#getencoded) and this API is as follows: 992> 993> 1. You can specify the format of the data to be obtained in this API. 994> 2. The format of the key to be obtained cannot be specified in [Key.getEncoded()](#getencoded). It must match that of the original data, which is the format of the key object generated by [convertKey](#convertkey-3). 995 996**Atomic service API**: This API can be used in atomic services since API version 12. 997 998**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 999 1000**Parameters** 1001 1002| Name| Type | Mandatory| Description | 1003| ---- | --------------------- | ---- | -------------------- | 1004| format | string | Yes | Format of the key. The value can be **X509\|COMPRESSED** or **X509\|UNCOMPRESSED** only.| 1005 1006**Return value** 1007 1008| Type | Description | 1009| --------------------------- | --------------------------------- | 1010| [DataBlob](#datablob) | Public key data obtained.| 1011 1012**Error codes** 1013For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 1014 1015| ID| Error Message | 1016| -------- | ---------------------- | 1017| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 1018| 17620001 | memory operation failed. | 1019| 17630001 | crypto operation error. | 1020 1021**Example** 1022 1023<!--code_no_check--> 1024```ts 1025let key: cryptoFramework.PubKey; // Key is a public key object. The generation process is omitted here. 1026let returnBlob = key.getEncodedDer('X509|UNCOMPRESSED'); 1027console.info('returnBlob data: ' + returnBlob.data); 1028``` 1029 1030### getEncodedPem<sup>12+</sup> 1031 1032getEncodedPem(format: string): string 1033 1034Obtains 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 and PKCS #1 specifications and be encoded in PEM. 1035 1036**Atomic service API**: This API can be used in atomic services since API version 12. 1037 1038**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 1039 1040**Parameters** 1041 1042| Name| Type | Mandatory| Description | 1043| ---- | --------------------- | ---- | -------------------- | 1044| format | string | Yes | Encoding format of the key data to obtain. The format for a public key can be **'PKCS1'** or **'X509'**.| 1045 1046**Return value** 1047 1048| Type | Description | 1049| --------------------------- | --------------------------------- | 1050| string | Key data obtained.| 1051 1052**Error codes** 1053For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 1054 1055| ID| Error Message | 1056| -------- | ---------------------- | 1057| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 1058| 17620001 | memory operation failed. | 1059| 17630001 | crypto operation error. | 1060 1061**Example** 1062 1063```ts 1064import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 1065 1066let publicPkcs1Str1024: string = 1067 "-----BEGIN RSA PUBLIC KEY-----\n" 1068 + "MIGJAoGBALAg3eavbX433pOjGdWdpL7HIr1w1EAeIcaCtuMfDpECPdX6X5ZjrwiE\n" 1069 + "h7cO51WXMT2gyN45DCQySr/8cLE2UiUVHo7qlrSatdLA9ETtgob3sJ4qTaBg5Lxg\n" 1070 + "SHy2gC+bvEpuIuRe64yXGuM/aP+ZvmIj9QBIVI9mJD8jLEOvQBBpAgMBAAE=\n" 1071 + "-----END RSA PUBLIC KEY-----\n"; 1072 1073function TestPubKeyPkcs1ToX509BySync1024() { 1074 let rsaGenerator = cryptoFramework.createAsyKeyGenerator('RSA1024'); 1075 let keyPair = rsaGenerator.convertPemKeySync(publicPkcs1Str1024, null); 1076 let pubPemKey = keyPair.pubKey; 1077 let pubString = pubPemKey.getEncodedPem('X509'); 1078 console.info("[sync]TestPubKeyPkcs1ToX509BySync1024 pubString output is " + pubString); 1079} 1080``` 1081 1082## PriKey 1083 1084Provides 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. 1085 1086The private key can be generated by using the asymmetric key generator [AsyKeyGenerator](#asykeygenerator) or [AsyKeyGeneratorBySpec](#asykeygeneratorbyspec10). 1087 1088### clearMem 1089 1090clearMem(): void 1091 1092Clear the keys in memory. This API returns the result synchronously. 1093 1094**Atomic service API**: This API can be used in atomic services since API version 12. 1095 1096**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 1097 1098The system capability is **SystemCapability.Security.CryptoFramework** in API versions 9 to 11, and **SystemCapability.Security.CryptoFramework.Key.AsymKey** since API version 12. 1099 1100**Example** 1101 1102<!--code_no_check--> 1103```ts 1104let key: cryptoFramework.PriKey; // The key is a private key generated by the asymmetric key generator. The generation process is omitted here. 1105key.clearMem(); // For the asymmetric private key, clearMem() releases the internal key struct. After clearMem is executed, getEncoded() is not supported. 1106``` 1107 1108### getAsyKeySpec<sup>10+</sup> 1109 1110getAsyKeySpec(itemType: AsyKeySpecItem): bigint | string | number 1111 1112Obtains a key parameter. This API returns the result synchronously. 1113 1114**Atomic service API**: This API can be used in atomic services since API version 12. 1115 1116**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 1117 1118The system capability is **SystemCapability.Security.CryptoFramework** in API versions 10 to 11, and **SystemCapability.Security.CryptoFramework.Key.AsymKey** since API version 12. 1119 1120**Parameters** 1121 1122| Name| Type | Mandatory| Description | 1123| ---- | --------------------- | ---- | -------------------- | 1124| itemType | [AsyKeySpecItem](#asykeyspecitem10) | Yes | Key parameter to obtain.| 1125 1126**Return value** 1127 1128| Type | Description | 1129| --------------------------- | --------------------------------- | 1130| bigint \| string \| number | Content of the key parameter obtained.| 1131 1132**Error codes** 1133For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 1134 1135| ID| Error Message | 1136| -------- | ---------------------- | 1137| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 1138| 801 | this operation is not supported. | 1139| 17620001 | memory operation failed. | 1140| 17630001 | crypto operation error. | 1141 1142**Example** 1143 1144<!--code_no_check--> 1145```ts 1146let key: cryptoFramework.PriKey; // key is a private key object. The generation process is omitted here. 1147let p = key.getAsyKeySpec(cryptoFramework.AsyKeySpecItem.ECC_FP_P_BN); 1148console.info('ecc item --- p: ' + p.toString(16)); 1149``` 1150### getEncodedDer<sup>12+</sup> 1151 1152getEncodedDer(format: string): DataBlob 1153 1154Obtains 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. 1155 1156> **NOTE** 1157> 1158> The difference between [Key.getEncoded()](#getencoded) and this API is as follows:<br> 1159> 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. 1160> 2. The format of the key data to be obtained cannot be specified in [Key.getEncoded()](#getencoded). 1161 1162**Atomic service API**: This API can be used in atomic services since API version 12. 1163 1164**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 1165 1166**Parameters** 1167 1168| Name| Type | Mandatory| Description | 1169| ---- | --------------------- | ---- | -------------------- | 1170| format | string | Yes | Format of the key. Currently, only **PKCS8** is supported.| 1171 1172**Return value** 1173 1174| Type | Description | 1175| --------------------------- | --------------------------------- | 1176| [DataBlob](#datablob) | ECC private key data obtained.| 1177 1178**Error codes** 1179For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 1180 1181| ID| Error Message | 1182| -------- | ---------------------- | 1183| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 1184| 17620001 | memory operation failed. | 1185| 17630001 | crypto operation error. | 1186 1187**Example** 1188 1189<!--code_no_check--> 1190```ts 1191let key: cryptoFramework.PriKey; // key is a private key object. The generation process is omitted here. 1192let returnBlob = key.getEncodedDer('PKCS8'); 1193console.info('returnBlob data: ' + returnBlob.data); 1194``` 1195 1196### getEncodedPem<sup>12+</sup> 1197 1198getEncodedPem(format: string): string 1199 1200Obtains 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 the PKCS #8 and PKCS #1 specifications and be encoded in PEM. 1201 1202**Atomic service API**: This API can be used in atomic services since API version 12. 1203 1204**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 1205 1206**Parameters** 1207 1208| Name| Type | Mandatory| Description | 1209| ---- | --------------------- | ---- | -------------------- | 1210| format | string | Yes | Encoding format of the key data to obtain. The format of a private key can be **'PKCS1'** or **'PKCS8'**.| 1211 1212**Return value** 1213 1214| Type | Description | 1215| --------------------------- | --------------------------------- | 1216| string | Key data obtained.| 1217 1218**Error codes** 1219For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 1220 1221| ID| Error Message | 1222| -------- | ---------------------- | 1223| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 1224| 17620001 | memory operation failed. | 1225| 17630001 | crypto operation error. | 1226 1227**Example** 1228 1229```ts 1230import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 1231 1232let priKeyPkcs1Str1024: string = 1233 "-----BEGIN RSA PRIVATE KEY-----\n" 1234 + "MIICXQIBAAKBgQCwIN3mr21+N96ToxnVnaS+xyK9cNRAHiHGgrbjHw6RAj3V+l+W\n" 1235 + "Y68IhIe3DudVlzE9oMjeOQwkMkq//HCxNlIlFR6O6pa0mrXSwPRE7YKG97CeKk2g\n" 1236 + "YOS8YEh8toAvm7xKbiLkXuuMlxrjP2j/mb5iI/UASFSPZiQ/IyxDr0AQaQIDAQAB\n" 1237 + "AoGAEvBFzBNa+7J4PXnRQlYEK/tvsd0bBZX33ceacMubHl6WVZbphltLq+fMTBPP\n" 1238 + "LjXmtpC+aJ7Lvmyl+wTi/TsxE9vxW5JnbuRT48rnZ/Xwq0eozDeEeIBRrpsr7Rvr\n" 1239 + "7ctrgzr4m4yMHq9aDgpxj8IR7oHkfwnmWr0wM3FuiVlj650CQQDineeNZ1hUTkj4\n" 1240 + "D3O+iCi3mxEVEeJrpqrmSFolRMb+iozrIRKuJlgcOs+Gqi2fHfOTTL7LkpYe8SVg\n" 1241 + "e3JxUdVLAkEAxvcZXk+byMFoetrnlcMR13VHUpoVeoV9qkv6CAWLlbMdgf7uKmgp\n" 1242 + "a1Yp3QPDNQQqkPvrqtfR19JWZ4uy1qREmwJALTU3BjyBoH/liqb6fh4HkWk75Som\n" 1243 + "MzeSjFIOubSYxhq5tgZpBZjcpvUMhV7Zrw54kwASZ+YcUJvmyvKViAm9NQJBAKF7\n" 1244 + "DyXSKrem8Ws0m1ybM7HQx5As6l3EVhePDmDQT1eyRbKp+xaD74nkJpnwYdB3jyyY\n" 1245 + "qc7A1tj5J5NmeEFolR0CQQCn76Xp8HCjGgLHw9vg7YyIL28y/XyfFyaZAzzK+Yia\n" 1246 + "akNwQ6NeGtXSsuGCcyyfpacHp9xy8qXQNKSkw03/5vDO\n" 1247 + "-----END RSA PRIVATE KEY-----\n"; 1248 1249function TestPriKeyPkcs1ToPkcs8BySync1024() { 1250 let rsaGenerator = cryptoFramework.createAsyKeyGenerator('RSA1024'); 1251 let keyPair = rsaGenerator.convertPemKeySync(null, priKeyPkcs1Str1024); 1252 let priPemKey = keyPair.priKey; 1253 let priString = priPemKey.getEncodedPem('PKCS8'); 1254 console.info("[sync]TestPriKeyPkcs1ToPkcs8BySync1024 priString output is " + priString); 1255} 1256``` 1257 1258### getEncodedPem<sup>18+</sup> 1259 1260getEncodedPem(format: string, config: KeyEncodingConfig): string 1261 1262Obtains 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 be encoded in PEM. 1263 1264**Atomic service API**: This API can be used in atomic services since API version 18. 1265 1266**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 1267 1268**Parameters** 1269 1270| Name| Type | Mandatory| Description | 1271| ---- | --------------------- | ---- | -------------------- | 1272| format | string | Yes | Encoding format of the key data to obtain. The format of a private key can be **'PKCS1'** or **'PKCS8'**.| 1273| config | [KeyEncodingConfig](#keyencodingconfig18) | Yes| Options (including the password and algorithm) for encoding the private key.| 1274 1275**Return value** 1276 1277| Type | Description | 1278| --------------------------- | --------------------------------- | 1279| string | Key data obtained. If **config** is specified, the key obtained is encoded.| 1280 1281**Error codes** 1282For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 1283 1284| ID| Error Message | 1285| -------- | ---------------------- | 1286| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 1287| 801 | this operation is not supported. | 1288| 17620001 | memory operation failed. | 1289| 17630001 | crypto operation error. | 1290 1291**Example** 1292 1293```ts 1294import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 1295 1296let priKeyPkcs1Str1024: string = 1297 "-----BEGIN RSA PRIVATE KEY-----\n" 1298 + "MIICXQIBAAKBgQCwIN3mr21+N96ToxnVnaS+xyK9cNRAHiHGgrbjHw6RAj3V+l+W\n" 1299 + "Y68IhIe3DudVlzE9oMjeOQwkMkq//HCxNlIlFR6O6pa0mrXSwPRE7YKG97CeKk2g\n" 1300 + "YOS8YEh8toAvm7xKbiLkXuuMlxrjP2j/mb5iI/UASFSPZiQ/IyxDr0AQaQIDAQAB\n" 1301 + "AoGAEvBFzBNa+7J4PXnRQlYEK/tvsd0bBZX33ceacMubHl6WVZbphltLq+fMTBPP\n" 1302 + "LjXmtpC+aJ7Lvmyl+wTi/TsxE9vxW5JnbuRT48rnZ/Xwq0eozDeEeIBRrpsr7Rvr\n" 1303 + "7ctrgzr4m4yMHq9aDgpxj8IR7oHkfwnmWr0wM3FuiVlj650CQQDineeNZ1hUTkj4\n" 1304 + "D3O+iCi3mxEVEeJrpqrmSFolRMb+iozrIRKuJlgcOs+Gqi2fHfOTTL7LkpYe8SVg\n" 1305 + "e3JxUdVLAkEAxvcZXk+byMFoetrnlcMR13VHUpoVeoV9qkv6CAWLlbMdgf7uKmgp\n" 1306 + "a1Yp3QPDNQQqkPvrqtfR19JWZ4uy1qREmwJALTU3BjyBoH/liqb6fh4HkWk75Som\n" 1307 + "MzeSjFIOubSYxhq5tgZpBZjcpvUMhV7Zrw54kwASZ+YcUJvmyvKViAm9NQJBAKF7\n" 1308 + "DyXSKrem8Ws0m1ybM7HQx5As6l3EVhePDmDQT1eyRbKp+xaD74nkJpnwYdB3jyyY\n" 1309 + "qc7A1tj5J5NmeEFolR0CQQCn76Xp8HCjGgLHw9vg7YyIL28y/XyfFyaZAzzK+Yia\n" 1310 + "akNwQ6NeGtXSsuGCcyyfpacHp9xy8qXQNKSkw03/5vDO\n" 1311 + "-----END RSA PRIVATE KEY-----\n"; 1312 1313function TestPriKeyPkcs1Encoded() { 1314 let rsaGenerator = cryptoFramework.createAsyKeyGenerator('RSA1024'); 1315 let keyPair = rsaGenerator.convertPemKeySync(null, priKeyPkcs1Str1024); 1316 let options : cryptoFramework.KeyEncodingConfig = { 1317 password: "123456", 1318 cipherName: "AES-128-CBC" 1319 } 1320 let priPemKey = keyPair.priKey; 1321 let priString = priPemKey.getEncodedPem('PKCS1', options); 1322 console.info("[sync]TestPriKeyPkcs1Encoded priString output is " + priString); 1323} 1324``` 1325 1326## KeyPair 1327 1328Defines an asymmetric key pair, which includes a public key and a private key. 1329 1330The asymmetric key pair can be generated by using the asymmetric key generator [AsyKeyGenerator](#asykeygenerator) or [AsyKeyGeneratorBySpec](#asykeygeneratorbyspec10). 1331 1332> **NOTE** 1333> 1334> The **pubKey** and **priKey** objects are members of the **KeyPair** object. When the **KeyPair** object is out of the scope, its **pubKey** and **priKey** objects will be destructed. 1335> 1336> The service must reference the **KeyPair** object instead of the internal **pubKey** or **priKey** object. 1337 1338### Attributes 1339 1340**Atomic service API**: This API can be used in atomic services since API version 12. 1341 1342**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 1343 1344The system capability is **SystemCapability.Security.CryptoFramework** in API versions 9 to 11, and **SystemCapability.Security.CryptoFramework.Key.AsymKey** since API version 12. 1345 1346| Name | Type | Read-Only| Optional| Description | 1347| ------- | ------ | ---- | ---- | ------------ | 1348| priKey | [PriKey](#prikey) | Yes | No | Private key. | 1349| pubKey | [PubKey](#pubkey) | Yes | No | Public key. | 1350 1351## cryptoFramework.createSymKeyGenerator 1352 1353createSymKeyGenerator(algName: string): SymKeyGenerator 1354 1355Creates a symmetric key generator instance with the specified algorithm. 1356 1357For details about the supported specifications, see [Symmetric Key Generation and Conversion Specifications](../../security/CryptoArchitectureKit/crypto-sym-key-generation-conversion-spec.md). 1358 1359**Atomic service API**: This API can be used in atomic services since API version 12. 1360 1361**System capability**: SystemCapability.Security.CryptoFramework.Key.SymKey 1362 1363The system capability is **SystemCapability.Security.CryptoFramework** in API versions 9 to 11, and **SystemCapability.Security.CryptoFramework.Key.SymKey** since API version 12. 1364 1365**Parameters** 1366 1367| Name | Type | Mandatory| Description | 1368| ------- | ------ | ---- | ------------------------------------------------------------ | 1369| algName | string | Yes | Algorithm to be used by 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).| 1370 1371**Return value** 1372 1373| Type | Description | 1374| ----------------------------------- | -------------------------- | 1375| [SymKeyGenerator](#symkeygenerator) | **symKeyGenerator** instance created.| 1376 1377**Error codes** 1378For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 1379 1380| ID| Error Message | 1381| -------- | ---------------------- | 1382| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 1383| 801 | this operation is not supported. | 1384 1385**Example** 1386 1387```ts 1388import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 1389 1390let symKeyGenerator = cryptoFramework.createSymKeyGenerator('3DES192'); 1391``` 1392 1393## SymKeyGenerator 1394 1395Provides APIs for using the **symKeyGenerator**. 1396 1397Before using the APIs of this class, use [createSymKeyGenerator](#cryptoframeworkcreatesymkeygenerator) to create a **SymKeyGenerator** instance. 1398 1399### Attributes 1400 1401**Atomic service API**: This API can be used in atomic services since API version 12. 1402 1403**System capability**: SystemCapability.Security.CryptoFramework.Key.SymKey 1404 1405The system capability is **SystemCapability.Security.CryptoFramework** in API versions 9 to 11, and **SystemCapability.Security.CryptoFramework.Key.SymKey** since API version 12. 1406 1407| Name | Type | Read-Only| Optional| Description | 1408| ------- | ------ | ---- | ---- | ------------------------------ | 1409| algName | string | Yes | No | Algorithm used by the **symKeyGenerator**.| 1410 1411### generateSymKey 1412 1413generateSymKey(callback: AsyncCallback\<SymKey>): void 1414 1415Generates a key randomly. This API uses an asynchronous callback to return the result. 1416 1417This API can be used only after a **symKeyGenerator** instance is created by using [createSymKeyGenerator](#cryptoframeworkcreatesymkeygenerator). 1418 1419**RAND_priv_bytes()** of OpenSSL can be used to generate random keys. 1420 1421> **NOTE** 1422> 1423> For symmetric keys used in the HMAC algorithm, if a hash algorithm (for example, **HMAC|SHA256**) is specified when the symmetric key generator is created, a binary key matching the hash length (for example, a 256-bit key) will be randomly generated. If no hash algorithm is specified, for example, only **HMAC** is specified, random symmetric key generation is not supported. You can generate symmetric key data using [convertKey](#convertkey). 1424 1425**Atomic service API**: This API can be used in atomic services since API version 12. 1426 1427**System capability**: SystemCapability.Security.CryptoFramework.Key.SymKey 1428 1429The system capability is **SystemCapability.Security.CryptoFramework** in API versions 9 to 11, and **SystemCapability.Security.CryptoFramework.Key.SymKey** since API version 12. 1430 1431**Parameters** 1432 1433| Name | Type | Mandatory| Description | 1434| -------- | --------------------------------- | ---- | ------------------------------------------------------------ | 1435| callback | AsyncCallback\<[SymKey](#symkey)> | Yes | Callback used 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.| 1436 1437**Error codes** 1438For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 1439 1440| ID| Error Message | 1441| -------- | ------------- | 1442| 17620001 | memory operation failed. | 1443 1444**Example** 1445 1446```ts 1447import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 1448 1449let symKeyGenerator = cryptoFramework.createSymKeyGenerator('3DES192'); 1450 symKeyGenerator.generateSymKey((err, symKey) => { 1451 console.info('Generate symKey success, algName: ' + symKey.algName); 1452 }); 1453``` 1454 1455### generateSymKey 1456 1457generateSymKey(): Promise\<SymKey> 1458 1459Generates a key randomly. This API uses a promise to return the result. 1460 1461This API can be used only after a **symKeyGenerator** instance is created by using [createSymKeyGenerator](#cryptoframeworkcreatesymkeygenerator). 1462 1463**RAND_priv_bytes()** of OpenSSL can be used to generate random keys. 1464 1465**Atomic service API**: This API can be used in atomic services since API version 12. 1466 1467**System capability**: SystemCapability.Security.CryptoFramework.Key.SymKey 1468 1469The system capability is **SystemCapability.Security.CryptoFramework** in API versions 9 to 11, and **SystemCapability.Security.CryptoFramework.Key.SymKey** since API version 12. 1470 1471**Return value** 1472 1473| Type | Description | 1474| --------------------------- | --------------------------------- | 1475| Promise\<[SymKey](#symkey)> | Promise used to return the symmetric key generated.| 1476 1477**Error codes** 1478For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 1479 1480| ID| Error Message | 1481| -------- | ------------- | 1482| 17620001 | memory operation failed. | 1483 1484**Example** 1485 1486```ts 1487import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 1488import { BusinessError } from '@kit.BasicServicesKit'; 1489 1490let symKeyGenerator = cryptoFramework.createSymKeyGenerator('AES128'); 1491 symKeyGenerator.generateSymKey() 1492 .then(symKey => { 1493 console.info('Generate symKey success, algName: ' + symKey.algName); 1494 }).catch((error: BusinessError) => { 1495 console.error(`Generate symKey failed, ${error.code}, ${error.message}`); 1496 }); 1497``` 1498 1499### generateSymKeySync<sup>12+</sup> 1500 1501generateSymKeySync(): SymKey 1502 1503Generates a symmetric key randomly. This API returns the result synchronously. 1504 1505This API can be used only after a **symKeyGenerator** instance is created by using [createSymKeyGenerator](#cryptoframeworkcreatesymkeygenerator). 1506 1507**RAND_priv_bytes()** of OpenSSL can be used to generate random keys. 1508 1509> **NOTE** 1510> 1511> For symmetric keys used in the HMAC algorithm, if a hash algorithm (for example, **HMAC|SHA256**) is specified when the symmetric key generator is created, a binary key matching the hash length (for example, a 256-bit key) will be randomly generated.<br>If no hash algorithm is specified, for example, only **HMAC** is specified, random symmetric key generation is not supported. You can generate symmetric key data using [convertKeySync](#convertkeysync12). 1512 1513**Atomic service API**: This API can be used in atomic services since API version 12. 1514 1515**System capability**: SystemCapability.Security.CryptoFramework.Key.SymKey 1516 1517**Return value** 1518 1519| Type | Description | 1520| --------------------------- | --------------------------------- | 1521| [SymKey](#symkey) | Symmetric key generated.| 1522 1523**Error codes** 1524For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 1525 1526| ID| Error Message | 1527| -------- | ------------- | 1528| 17620001 | memory operation failed. | 1529 1530**Example** 1531 1532```ts 1533import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 1534 1535function testGenerateSymKeySync() { 1536 // Create a SymKeyGenerator instance. 1537 let symKeyGenerator = cryptoFramework.createSymKeyGenerator('AES256'); 1538 // Use SymKeyGenerator to randomly generate a symmetric key. 1539 let key = symKeyGenerator.generateSymKeySync(); 1540 let encodedKey = key.getEncoded(); 1541 console.info('key hex:' + encodedKey.data); 1542} 1543``` 1544 1545### convertKey 1546 1547convertKey(key: DataBlob, callback: AsyncCallback\<SymKey>): void 1548 1549Converts data into a symmetric key. This API uses an asynchronous callback to return the result. 1550 1551This API can be used only after a **symKeyGenerator** instance is created by using [createSymKeyGenerator](#cryptoframeworkcreatesymkeygenerator). 1552 1553> **NOTE** 1554> 1555> For symmetric keys used in the HMAC algorithm, if a hash algorithm (for example, **HMAC|SHA256**) is specified when the symmetric key generator is created, the binary key data passed in must match the hash length (for example, a 256-bit key for SHA256).<br>If no hash algorithm is specified when the symmetric key generator is created (for example, only **HMAC** is specified), any binary key data with a length of 1 to 4096 bytes is supported. 1556 1557**Atomic service API**: This API can be used in atomic services since API version 12. 1558 1559**System capability**: SystemCapability.Security.CryptoFramework.Key.SymKey 1560 1561The system capability is **SystemCapability.Security.CryptoFramework** in API versions 9 to 11, and **SystemCapability.Security.CryptoFramework.Key.SymKey** since API version 12. 1562 1563**Parameters** 1564 1565| Name | Type | Mandatory| Description | 1566| -------- | ------------------- | ---- | ---------------------| 1567| key | [DataBlob](#datablob) | Yes | Data to convert. | 1568| callback | AsyncCallback\<[SymKey](#symkey)> | Yes | Callback used 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.| 1569 1570**Error codes** 1571For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 1572 1573| ID| Error Message | 1574| -------- | --------------------------------------------------- | 1575| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 1576| 17620001 | memory operation failed. | 1577 1578**Example** 1579 1580```ts 1581import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 1582 1583function genKeyMaterialBlob(): cryptoFramework.DataBlob { 1584 let arr = [ 1585 0xba, 0x3d, 0xc2, 0x71, 0x21, 0x1e, 0x30, 0x56, 1586 0xad, 0x47, 0xfc, 0x5a, 0x46, 0x39, 0xee, 0x7c, 1587 0xba, 0x3b, 0xc2, 0x71, 0xab, 0xa0, 0x30, 0x72]; // keyLen = 192 (24 bytes) 1588 let keyMaterial = new Uint8Array(arr); 1589 return { data: keyMaterial }; 1590} 1591 1592function testConvertKey() { 1593 let symKeyGenerator = cryptoFramework.createSymKeyGenerator('3DES192'); 1594 let keyMaterialBlob = genKeyMaterialBlob(); 1595 symKeyGenerator.convertKey(keyMaterialBlob, (err, symKey) => { 1596 console.info('Convert symKey success, algName: ' + symKey.algName); 1597 }); 1598} 1599``` 1600 1601### convertKey 1602 1603convertKey(key: DataBlob): Promise\<SymKey> 1604 1605Converts data into a symmetric key. This API uses a promise to return the result. 1606 1607Before using this API, create a symmetric key generator by using [createSymKeyGenerator](#cryptoframeworkcreatesymkeygenerator). 1608 1609**Atomic service API**: This API can be used in atomic services since API version 12. 1610 1611**System capability**: SystemCapability.Security.CryptoFramework.Key.SymKey 1612 1613The system capability is **SystemCapability.Security.CryptoFramework** in API versions 9 to 11, and **SystemCapability.Security.CryptoFramework.Key.SymKey** since API version 12. 1614 1615**Parameters** 1616 1617| Name| Type | Mandatory| Description | 1618| ---- | --------------------- | ---- | -------------------- | 1619| key | [DataBlob](#datablob) | Yes | Data to convert.| 1620 1621**Return value** 1622 1623| Type | Description | 1624| --------------------------- | --------------------------------- | 1625| Promise\<[SymKey](#symkey)> | Promise used to return the symmetric key generated.| 1626 1627**Error codes** 1628For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 1629 1630| ID| Error Message | 1631| -------- | --------------------------------------------- | 1632| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 1633| 17620001 | memory operation failed. | 1634 1635**Example** 1636 1637```ts 1638import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 1639import { BusinessError } from '@kit.BasicServicesKit'; 1640 1641function genKeyMaterialBlob(): cryptoFramework.DataBlob { 1642 let arr = [ 1643 0xba, 0x3d, 0xc2, 0x71, 0x21, 0x1e, 0x30, 0x56, 1644 0xad, 0x47, 0xfc, 0x5a, 0x46, 0x39, 0xee, 0x7c, 1645 0xba, 0x3b, 0xc2, 0x71, 0xab, 0xa0, 0x30, 0x72]; // keyLen = 192 (24 bytes) 1646 let keyMaterial = new Uint8Array(arr); 1647 return { data: keyMaterial }; 1648} 1649 1650function testConvertKey() { 1651 let symKeyGenerator = cryptoFramework.createSymKeyGenerator('3DES192'); 1652 let keyMaterialBlob = genKeyMaterialBlob(); 1653 symKeyGenerator.convertKey(keyMaterialBlob) 1654 .then(symKey => { 1655 console.info('Convert symKey success, algName: ' + symKey.algName); 1656 }).catch((error: BusinessError) => { 1657 console.error(`Convert symKey failed, ${error.code}, ${error.message}`); 1658 }); 1659} 1660``` 1661 1662### convertKeySync<sup>12+</sup> 1663 1664convertKeySync(key: DataBlob): SymKey 1665 1666Converts data into a symmetric key. This API returns the result synchronously. 1667 1668This API can be used only after a **symKeyGenerator** instance is created by using [createSymKeyGenerator](#cryptoframeworkcreatesymkeygenerator). 1669 1670> **NOTE** 1671> 1672> For symmetric keys used in the HMAC algorithm, if a hash algorithm (for example, **HMAC|SHA256**) is specified when the symmetric key generator is created, the binary key data passed in must match the hash length (for example, a 256-bit key for SHA256). If no hash algorithm is specified when the symmetric key generator is created (for example, only **HMAC** is specified), any binary key data with a length of 1 to 4096 bytes is supported. 1673 1674**Atomic service API**: This API can be used in atomic services since API version 12. 1675 1676**System capability**: SystemCapability.Security.CryptoFramework.Key.SymKey 1677 1678**Parameters** 1679 1680| Name | Type | Mandatory| Description | 1681| -------- | ------------------- | ---- | ---------------------| 1682| key | [DataBlob](#datablob) | Yes | Data to convert. | 1683 1684**Return value** 1685 1686| Type | Description | 1687| --------------------------- | --------------------------------- | 1688| [SymKey](#symkey) | Symmetric key obtained.| 1689 1690**Error codes** 1691For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 1692 1693| ID| Error Message | 1694| -------- | --------------------------------------------------- | 1695| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 1696| 17620001 | memory operation failed. | 1697 1698**Example** 1699 1700```ts 1701import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 1702import { buffer } from '@kit.ArkTS'; 1703 1704function testConvertKeySync() { 1705 // The symmetric key length is 64 bytes (512 bits). 1706 let keyMessage = '87654321abcdefgh87654321abcdefgh87654321abcdefgh87654321abcdefgh'; 1707 let keyBlob: cryptoFramework.DataBlob = { 1708 data : new Uint8Array(buffer.from(keyMessage, 'utf-8').buffer) 1709 } 1710 let symKeyGenerator = cryptoFramework.createSymKeyGenerator('HMAC'); 1711 let key = symKeyGenerator.convertKeySync(keyBlob); 1712 let encodedKey = key.getEncoded(); 1713 console.info('key encoded data: ' + encodedKey.data); 1714} 1715``` 1716 1717## cryptoFramework.createAsyKeyGenerator 1718 1719createAsyKeyGenerator(algName: string): AsyKeyGenerator 1720 1721Creates an **AsyKeyGenerator** instance based on the specified algorithm. 1722 1723For details about the supported specifications, see [Asymmetric Key Generation and Conversion Specifications](../../security/CryptoArchitectureKit/crypto-asym-key-generation-conversion-spec.md). 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 system capability is **SystemCapability.Security.CryptoFramework** in API versions 9 to 11, and **SystemCapability.Security.CryptoFramework.Key.AsymKey** since API version 12. 1730 1731**Parameters** 1732 1733| Name | Type | Mandatory| Description | 1734| ------- | ------ | ---- | -------------------------------- | 1735| algName | string | Yes | [Algorithm used to generate an asymmetric key pair](../../security/CryptoArchitectureKit/crypto-asym-key-generation-conversion-spec.md).| 1736 1737**Return value** 1738 1739| Type | Description | 1740| --------------- | ---------------------------- | 1741| [AsyKeyGenerator](#asykeygenerator) | **AsyKeyGenerator** instance created. | 1742 1743**Error codes** 1744For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 1745 1746| ID| Error Message | 1747| -------- | ---------------------- | 1748| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 1749| 801 | this operation is not supported. | 1750| 17620001 | memory operation failed. | 1751 1752**Example** 1753 1754```ts 1755import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 1756 1757let asyKeyGenerator = cryptoFramework.createAsyKeyGenerator('ECC256'); 1758``` 1759 1760## AsyKeyGenerator 1761 1762Provides APIs for using the **AsKeyGenerator**. Before using any API of the **AsKeyGenerator** class, you must create an **AsyKeyGenerator** instance by using **createAsyKeyGenerator()**. 1763 1764### Attributes 1765 1766**Atomic service API**: This API can be used in atomic services since API version 12. 1767 1768**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 1769 1770The system capability is **SystemCapability.Security.CryptoFramework** in API versions 9 to 11, and **SystemCapability.Security.CryptoFramework.Key.AsymKey** since API version 12. 1771 1772| Name | Type | Read-Only| Optional| Description | 1773| ------- | ------ | ---- | ---- | -------------------------------- | 1774| algName | string | Yes | No | Algorithm used by the **AsKeyGenerator**.| 1775 1776### generateKeyPair 1777 1778generateKeyPair(callback: AsyncCallback\<KeyPair>): void 1779 1780Generates a key pair randomly. This API uses an asynchronous callback to return the result. 1781 1782**Atomic service API**: This API can be used in atomic services since API version 12. 1783 1784**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 1785 1786The system capability is **SystemCapability.Security.CryptoFramework** in API versions 9 to 11, and **SystemCapability.Security.CryptoFramework.Key.AsymKey** since API version 12. 1787 1788**Parameters** 1789 1790| Name | Type | Mandatory| Description | 1791| -------- | ----------------------- | ---- | ------------------------------ | 1792| callback | AsyncCallback\<[KeyPair](#keypair)> | Yes | Callback used to return the key pair obtained.| 1793 1794**Error codes** 1795For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 1796 1797| ID| Error Message | 1798| -------- | ---------------------- | 1799| 401 | invalid parameters. Possible causes: <br>Incorrect parameter types;| 1800| 17620001 | memory operation failed. | 1801| 17630001 | crypto operation error. | 1802 1803**Example** 1804 1805```ts 1806import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 1807 1808let asyKeyGenerator = cryptoFramework.createAsyKeyGenerator('ECC256'); 1809asyKeyGenerator.generateKeyPair((err, keyPair) => { 1810 if (err) { 1811 console.error("generateKeyPair: error."); 1812 return; 1813 } 1814 console.info('generateKeyPair: success.'); 1815}) 1816``` 1817 1818### generateKeyPair 1819 1820generateKeyPair(): Promise\<KeyPair> 1821 1822Generates an asymmetric key pair randomly. This API uses a promise to return the result. 1823 1824**Atomic service API**: This API can be used in atomic services since API version 12. 1825 1826**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 1827 1828The system capability is **SystemCapability.Security.CryptoFramework** in API versions 9 to 11, and **SystemCapability.Security.CryptoFramework.Key.AsymKey** since API version 12. 1829 1830**Return value** 1831 1832| Type | Description | 1833| ----------------- | --------------------------------- | 1834| Promise\<[KeyPair](#keypair)> | Promise used to return the key pair generated.| 1835 1836**Error codes** 1837For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 1838 1839| ID| Error Message | 1840| -------- | ---------------------- | 1841| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed. | 1842| 17620001 | memory operation failed. | 1843| 17630001 | crypto operation error. | 1844 1845**Example** 1846 1847```ts 1848import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 1849import { BusinessError } from '@kit.BasicServicesKit'; 1850 1851let asyKeyGenerator = cryptoFramework.createAsyKeyGenerator('ECC256'); 1852let keyGenPromise = asyKeyGenerator.generateKeyPair(); 1853keyGenPromise.then(keyPair => { 1854 console.info('generateKeyPair success.'); 1855}).catch((error: BusinessError) => { 1856 console.error("generateKeyPair error."); 1857}); 1858``` 1859 1860### generateKeyPairSync<sup>12+</sup> 1861 1862generateKeyPairSync(): KeyPair 1863 1864Generates an asymmetric key pair randomly. This API returns the result synchronously. 1865 1866**Atomic service API**: This API can be used in atomic services since API version 12. 1867 1868**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 1869 1870**Return value** 1871 1872| Type | Description | 1873| ----------------- | --------------------------------- | 1874| [KeyPair](#keypair) | Asymmetric key pair generated.| 1875 1876**Error codes** 1877For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 1878 1879| ID| Error Message | 1880| -------- | ---------------------- | 1881| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed. | 1882| 17620001 | memory operation failed. | 1883| 17630001 | crypto operation error. | 1884 1885**Example** 1886 1887```ts 1888import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 1889 1890let asyKeyGenerator = cryptoFramework.createAsyKeyGenerator('ECC256'); 1891try { 1892 let keyPairData = asyKeyGenerator.generateKeyPairSync(); 1893 if (keyPairData != null) { 1894 console.info('[Sync]: key pair success'); 1895 } else { 1896 console.error("[Sync]: get key pair result fail!"); 1897 } 1898} catch (e) { 1899 console.error(`sync error, ${e.code}, ${e.message}`); 1900} 1901``` 1902 1903### convertKey 1904 1905convertKey(pubKey: DataBlob | null, priKey: DataBlob | null, callback: AsyncCallback\<KeyPair\>): void 1906 1907Converts data into an asymmetric key. This API uses an asynchronous callback to return the result. For details, see **Key Conversion**. 1908 1909**Atomic service API**: This API can be used in atomic services since API version 12. 1910 1911**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 1912 1913The system capability is **SystemCapability.Security.CryptoFramework** in API versions 9 to 11, and **SystemCapability.Security.CryptoFramework.Key.AsymKey** since API version 12. 1914 1915**Parameters** 1916 1917| Name | Type | Mandatory| Description | 1918| -------- | ----------- | ---- | ------------------------------ | 1919| 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. | 1920| 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. | 1921| callback | AsyncCallback\<[KeyPair](#keypair)> | Yes | Callback used to return the key pair obtained.| 1922 1923**Error codes** 1924For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 1925 1926| ID| Error Message | 1927| -------- | ---------------------- | 1928| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 1929| 17620001 | memory operation failed. | 1930| 17630001 | crypto operation error. | 1931 1932**Example** 1933 1934```ts 1935import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 1936 1937let 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]); 1938let 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]); 1939let pubKeyBlob: cryptoFramework.DataBlob = { data: pubKeyArray }; // Binary data of the public key. 1940let priKeyBlob: cryptoFramework.DataBlob = { data: priKeyArray }; // Binary data of the private key. 1941let asyKeyGenerator = cryptoFramework.createAsyKeyGenerator('ECC256'); 1942asyKeyGenerator.convertKey(pubKeyBlob, priKeyBlob, (err, keyPair) => { 1943 if (err) { 1944 console.error("convertKey: error."); 1945 return; 1946 } 1947 console.info('convertKey: success.'); 1948}); 1949``` 1950 1951### convertKey 1952 1953convertKey(pubKey: DataBlob | null, priKey: DataBlob | null): Promise\<KeyPair> 1954 1955Converts data into an asymmetric key. This API uses a promise to return the result. For details, see **Key Conversion**. 1956 1957**Atomic service API**: This API can be used in atomic services since API version 12. 1958 1959**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 1960 1961The system capability is **SystemCapability.Security.CryptoFramework** in API versions 9 to 11, and **SystemCapability.Security.CryptoFramework.Key.AsymKey** since API version 12. 1962 1963**Parameters** 1964 1965| Name | Type | Mandatory| Description | 1966| ------ | -------- | ---- | ---------------- | 1967| 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.| 1968| 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.| 1969 1970**Return value** 1971 1972| Type | Description | 1973| ----------------- | --------------------------------- | 1974| Promise\<[KeyPair](#keypair)> | Promise used to return the key pair generated.| 1975 1976**Error codes** 1977For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 1978 1979| ID| Error Message | 1980| -------- | ---------------------- | 1981| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 1982| 17620001 | memory operation failed. | 1983| 17630001 | crypto operation error. | 1984 1985**Example** 1986 1987```ts 1988import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 1989import { BusinessError } from '@kit.BasicServicesKit'; 1990 1991let 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]); 1992let 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]); 1993let pubKeyBlob: cryptoFramework.DataBlob = { data: pubKeyArray }; // Binary data of the public key. 1994let priKeyBlob: cryptoFramework.DataBlob = { data: priKeyArray }; // Binary data of the private key. 1995let asyKeyGenerator = cryptoFramework.createAsyKeyGenerator('ECC256'); 1996let keyGenPromise = asyKeyGenerator.convertKey(pubKeyBlob, priKeyBlob); 1997keyGenPromise.then(keyPair => { 1998 console.info('convertKey success.'); 1999}).catch((error: BusinessError) => { 2000 console.error("convertKey error."); 2001}); 2002``` 2003 2004### convertKeySync<sup>12+</sup> 2005 2006convertKeySync(pubKey: DataBlob | null, priKey: DataBlob | null): KeyPair 2007 2008Converts data into an asymmetric key pair. This API returns the result synchronously. For details, see **Key Conversion**. 2009 2010**Atomic service API**: This API can be used in atomic services since API version 12. 2011 2012**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 2013 2014**Parameters** 2015 2016| Name | Type | Mandatory| Description | 2017| ------ | -------- | ---- | ---------------- | 2018| pubKey | [DataBlob](#datablob) \| null<sup>10+</sup> | Yes | Public key material. If the public key does not need to be converted, pass in **null**. Before API version 10, only **DataBlob** is supported. Since API version 10s, **null** can be passed in.| 2019| priKey | [DataBlob](#datablob) \| null<sup>10+</sup> | Yes | Private key material. Before API version 10, only **DataBlob** is supported. Since API version 10s, **null** can be passed in.| 2020 2021**Return value** 2022 2023| Type | Description | 2024| ----------------- | --------------------------------- | 2025| [KeyPair](#keypair) | Asymmetric key pair generated.| 2026 2027**Error codes** 2028For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 2029 2030| ID| Error Message | 2031| -------- | ---------------------- | 2032| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 2033| 17620001 | memory operation failed. | 2034| 17630001 | crypto operation error. | 2035 2036**Example** 2037 2038```ts 2039import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 2040 2041let 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]); 2042let 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]); 2043let pubKeyBlob: cryptoFramework.DataBlob = { data: pubKeyArray }; // Binary data of the public key. 2044let priKeyBlob: cryptoFramework.DataBlob = { data: priKeyArray }; // Binary data of the private key. 2045let asyKeyGenerator = cryptoFramework.createAsyKeyGenerator('ECC256'); 2046try { 2047 let keyPairData = asyKeyGenerator.convertKeySync(pubKeyBlob, priKeyBlob); 2048 if (keyPairData != null) { 2049 console.info('[Sync]: key pair success'); 2050 } else { 2051 console.error("[Sync]: convert key pair result fail!"); 2052 } 2053} catch (e) { 2054 console.error(`sync error, ${e.code}, ${e.message}`); 2055} 2056``` 2057 2058**Key Conversion** 2059 20601. For asymmetric keys (RSA, ECC, and DSA), calling **getEncoded()** on the public key returns binary data in X.509 format, and calling **getEncoded()** on the private key returns binary data in PKCS #8 format. For ECC private keys, the data returned is in the format defined in RFC 5915. These key data can be passed across applications and stored persistently. 20612. 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. 20623. 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. 20634. 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. 2064 2065### convertPemKey<sup>12+</sup> 2066 2067convertPemKey(pubKey: string | null, priKey: string | null): Promise\<KeyPair> 2068 2069Converts data into an asymmetric key. This API uses a promise to return the result. 2070 2071> **NOTE** 2072> 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. 2073> 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. 2074> 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. 2075 2076**Atomic service API**: This API can be used in atomic services since API version 12. 2077 2078**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 2079 2080**Parameters** 2081 2082| Name | Type | Mandatory| Description | 2083| ------ | -------- | ---- | ---------------- | 2084| pubKey | string \| null | Yes | Public key material to convert. If no public key is required, set this parameter to **null**.| 2085| 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.| 2086 2087**Return value** 2088 2089| Type | Description | 2090| ----------------- | --------------------------------- | 2091| Promise\<[KeyPair](#keypair)> | Promise used to return the key pair generated.| 2092 2093**Error codes** 2094For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 2095 2096| ID| Error Message | 2097| -------- | ---------------------- | 2098| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed. | 2099| 17620001 | memory operation failed. | 2100| 17630001 | crypto operation error. | 2101 2102**Example** 2103 2104```ts 2105import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 2106import { BusinessError } from '@kit.BasicServicesKit'; 2107 2108let priKeyPkcs1Str1024: string = 2109 "-----BEGIN RSA PRIVATE KEY-----\n" 2110 + "MIICXQIBAAKBgQCwIN3mr21+N96ToxnVnaS+xyK9cNRAHiHGgrbjHw6RAj3V+l+W\n" 2111 + "Y68IhIe3DudVlzE9oMjeOQwkMkq//HCxNlIlFR6O6pa0mrXSwPRE7YKG97CeKk2g\n" 2112 + "YOS8YEh8toAvm7xKbiLkXuuMlxrjP2j/mb5iI/UASFSPZiQ/IyxDr0AQaQIDAQAB\n" 2113 + "AoGAEvBFzBNa+7J4PXnRQlYEK/tvsd0bBZX33ceacMubHl6WVZbphltLq+fMTBPP\n" 2114 + "LjXmtpC+aJ7Lvmyl+wTi/TsxE9vxW5JnbuRT48rnZ/Xwq0eozDeEeIBRrpsr7Rvr\n" 2115 + "7ctrgzr4m4yMHq9aDgpxj8IR7oHkfwnmWr0wM3FuiVlj650CQQDineeNZ1hUTkj4\n" 2116 + "D3O+iCi3mxEVEeJrpqrmSFolRMb+iozrIRKuJlgcOs+Gqi2fHfOTTL7LkpYe8SVg\n" 2117 + "e3JxUdVLAkEAxvcZXk+byMFoetrnlcMR13VHUpoVeoV9qkv6CAWLlbMdgf7uKmgp\n" 2118 + "a1Yp3QPDNQQqkPvrqtfR19JWZ4uy1qREmwJALTU3BjyBoH/liqb6fh4HkWk75Som\n" 2119 + "MzeSjFIOubSYxhq5tgZpBZjcpvUMhV7Zrw54kwASZ+YcUJvmyvKViAm9NQJBAKF7\n" 2120 + "DyXSKrem8Ws0m1ybM7HQx5As6l3EVhePDmDQT1eyRbKp+xaD74nkJpnwYdB3jyyY\n" 2121 + "qc7A1tj5J5NmeEFolR0CQQCn76Xp8HCjGgLHw9vg7YyIL28y/XyfFyaZAzzK+Yia\n" 2122 + "akNwQ6NeGtXSsuGCcyyfpacHp9xy8qXQNKSkw03/5vDO\n" 2123 + "-----END RSA PRIVATE KEY-----\n"; 2124let publicPkcs1Str1024: string = 2125 "-----BEGIN RSA PUBLIC KEY-----\n" 2126 + "MIGJAoGBALAg3eavbX433pOjGdWdpL7HIr1w1EAeIcaCtuMfDpECPdX6X5ZjrwiE\n" 2127 + "h7cO51WXMT2gyN45DCQySr/8cLE2UiUVHo7qlrSatdLA9ETtgob3sJ4qTaBg5Lxg\n" 2128 + "SHy2gC+bvEpuIuRe64yXGuM/aP+ZvmIj9QBIVI9mJD8jLEOvQBBpAgMBAAE=\n" 2129 + "-----END RSA PUBLIC KEY-----\n"; 2130async function TestConvertPemKeyByPromise() { 2131 let asyKeyGenerator = cryptoFramework.createAsyKeyGenerator('RSA1024'); 2132 asyKeyGenerator.convertPemKey(publicPkcs1Str1024, priKeyPkcs1Str1024) 2133 .then(keyPair => { 2134 console.info('convertPemKey success.'); 2135 }).catch((error: BusinessError) => { 2136 console.error("convertPemKey error."); 2137 }); 2138} 2139``` 2140 2141### convertPemKey<sup>18+</sup> 2142 2143convertPemKey(pubKey: string | null, priKey: string | null, password: string): Promise\<KeyPair> 2144 2145Converts data into an asymmetric key. This API uses a promise to return the result. 2146 2147> **NOTE** 2148> 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. 2149> 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. 2150> 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. 2151> 4. If **password** is passed in, it can be used to decrypt the encrypted private key. 2152 2153**Atomic service API**: This API can be used in atomic services since API version 18. 2154 2155**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 2156 2157**Parameters** 2158 2159| Name | Type | Mandatory| Description | 2160| ------ | -------- | ---- | ---------------- | 2161| pubKey | string \| null | Yes | Public key material to convert. If no public key is required, set this parameter to **null**.| 2162| 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.| 2163| password | string | Yes| Password used to decrypt the private key.| 2164 2165**Return value** 2166 2167| Type | Description | 2168| ----------------- | --------------------------------- | 2169| Promise\<[KeyPair](#keypair)> | Promise used to return the key pair generated.| 2170 2171**Error codes** 2172For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 2173 2174| ID| Error Message | 2175| -------- | ---------------------- | 2176| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed. | 2177| 17620001 | memory operation failed. | 2178| 17630001 | crypto operation error. | 2179 2180**Example** 2181 2182```ts 2183import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 2184import { BusinessError } from '@kit.BasicServicesKit'; 2185 2186let priKeyPkcs1EncodingStr : string = 2187 "-----BEGIN RSA PRIVATE KEY-----\n" 2188 +"Proc-Type: 4,ENCRYPTED\n" 2189 +"DEK-Info: AES-128-CBC,815A066131BF05CF87CE610A59CC69AE\n\n" 2190 +"7Jd0vmOmYGFZ2yRY8fqRl3+6rQlFtNcMILvcb5KWHDSrxA0ULmJE7CW0DSRikHoA\n" 2191 +"t0KgafhYXeQXh0dRy9lvVRAFSLHCLJVjchx90V7ZSivBFEq7+iTozVp4AlbgYsJP\n" 2192 +"vx/1sfZD2WAcyMJ7IDmJyft7xnpVSXsyWGTT4f3eaHJIh1dqjwrso7ucAW0FK6rp\n" 2193 +"/TONyOoXNfXtRbVtxNyCWBxt4HCSclDZFvS9y8fz9ZwmCUV7jei/YdzyQI2wnE13\n" 2194 +"W8cKlpzRFL6BWi8XPrUtAw5MWeHBAPUgPWMfcmiaeyi5BJFhQCrHLi+Gj4EEJvp7\n" 2195 +"mP5cbnQAx6+paV5z9m71SKrI/WSc4ixsYYdVmlL/qwAK9YliFfoPl030YJWW6rFf\n" 2196 +"T7J9BUlHGUJ0RB2lURNNLakM+UZRkeE9TByzCzgTxuQtyv5Lwsh2mAk3ia5x0kUO\n" 2197 +"LHg3Eoabhdh+YZA5hHaxnpF7VjspB78E0F9Btq+A41rSJ6zDOdToHey4MJ2nxdey\n" 2198 +"Z3bi81TZ6Fp4IuROrvZ2B/Xl3uNKR7n+AHRKnaAO87ywzyltvjwSh2y3xhJueiRs\n" 2199 +"BiYkyL3/fnocD3pexTdN6h3JgQGgO5GV8zw/NrxA85mw8o9im0HreuFObmNj36T9\n" 2200 +"k5N+R/QIXW83cIQOLaWK1ThYcluytf0tDRiMoKqULiaA6HvDMigExLxuhCtnoF8I\n" 2201 +"iOLN1cPdEVQjzwDHLqXP2DbWW1z9iRepLZlEm1hLRLEmOrTGKezYupVv306SSa6J\n" 2202 +"OA55lAeXMbyjFaYCr54HWrpt4NwNBX1efMUURc+1LcHpzFrBTTLbfjIyq6as49pH\n" 2203 +"-----END RSA PRIVATE KEY-----\n" 2204 2205async function TestConvertPemKeyByPromise() { 2206 let asyKeyGenerator = cryptoFramework.createAsyKeyGenerator('RSA1024'); 2207 asyKeyGenerator.convertPemKey(null, priKeyPkcs1EncodingStr, "123456") 2208 .then(keyPair => { 2209 console.info('convertPemKey success.'); 2210 }).catch((error: BusinessError) => { 2211 console.error("convertPemKey error."); 2212 }); 2213} 2214``` 2215 2216### convertPemKeySync<sup>12+</sup> 2217 2218convertPemKeySync(pubKey: string | null, priKey: string | null): KeyPair 2219 2220Converts data into an asymmetric key pair. This API returns the result synchronously. 2221 2222> **NOTE** 2223> The precautions for using **convertPemKeySync** are the same as those for **convertPemKey**. For details, see the description of [convertPemKey](#convertpemkey12). 2224 2225**Atomic service API**: This API can be used in atomic services since API version 12. 2226 2227**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 2228 2229**Parameters** 2230 2231| Name | Type | Mandatory| Description | 2232| ------ | -------- | ---- | ---------------- | 2233| pubKey | string \| null| Yes | Public key material to convert. If no public key is required, set this parameter to **null**.| 2234| priKey | string \| null| Yes | Private key material. If the private key does not need to be converted, you can pass in **null**. <br>**NOTE**: **pubKey** and **priKey** cannot be **null** at the same time.| 2235 2236**Return value** 2237 2238| Type | Description | 2239| ----------------- | --------------------------------- | 2240| [KeyPair](#keypair) | Asymmetric key pair generated.| 2241 2242**Error codes** 2243For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 2244 2245| ID| Error Message | 2246| -------- | ---------------------- | 2247| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed. | 2248| 17620001 | memory operation failed. | 2249| 17630001 | crypto operation error. | 2250 2251**Example** 2252 2253```ts 2254import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 2255import { BusinessError } from '@kit.BasicServicesKit'; 2256 2257let priKeyPkcs1Str1024: string = 2258 "-----BEGIN RSA PRIVATE KEY-----\n" 2259 + "MIICXQIBAAKBgQCwIN3mr21+N96ToxnVnaS+xyK9cNRAHiHGgrbjHw6RAj3V+l+W\n" 2260 + "Y68IhIe3DudVlzE9oMjeOQwkMkq//HCxNlIlFR6O6pa0mrXSwPRE7YKG97CeKk2g\n" 2261 + "YOS8YEh8toAvm7xKbiLkXuuMlxrjP2j/mb5iI/UASFSPZiQ/IyxDr0AQaQIDAQAB\n" 2262 + "AoGAEvBFzBNa+7J4PXnRQlYEK/tvsd0bBZX33ceacMubHl6WVZbphltLq+fMTBPP\n" 2263 + "LjXmtpC+aJ7Lvmyl+wTi/TsxE9vxW5JnbuRT48rnZ/Xwq0eozDeEeIBRrpsr7Rvr\n" 2264 + "7ctrgzr4m4yMHq9aDgpxj8IR7oHkfwnmWr0wM3FuiVlj650CQQDineeNZ1hUTkj4\n" 2265 + "D3O+iCi3mxEVEeJrpqrmSFolRMb+iozrIRKuJlgcOs+Gqi2fHfOTTL7LkpYe8SVg\n" 2266 + "e3JxUdVLAkEAxvcZXk+byMFoetrnlcMR13VHUpoVeoV9qkv6CAWLlbMdgf7uKmgp\n" 2267 + "a1Yp3QPDNQQqkPvrqtfR19JWZ4uy1qREmwJALTU3BjyBoH/liqb6fh4HkWk75Som\n" 2268 + "MzeSjFIOubSYxhq5tgZpBZjcpvUMhV7Zrw54kwASZ+YcUJvmyvKViAm9NQJBAKF7\n" 2269 + "DyXSKrem8Ws0m1ybM7HQx5As6l3EVhePDmDQT1eyRbKp+xaD74nkJpnwYdB3jyyY\n" 2270 + "qc7A1tj5J5NmeEFolR0CQQCn76Xp8HCjGgLHw9vg7YyIL28y/XyfFyaZAzzK+Yia\n" 2271 + "akNwQ6NeGtXSsuGCcyyfpacHp9xy8qXQNKSkw03/5vDO\n" 2272 + "-----END RSA PRIVATE KEY-----\n"; 2273 let publicPkcs1Str1024: string = 2274 "-----BEGIN RSA PUBLIC KEY-----\n" 2275 + "MIGJAoGBALAg3eavbX433pOjGdWdpL7HIr1w1EAeIcaCtuMfDpECPdX6X5ZjrwiE\n" 2276 + "h7cO51WXMT2gyN45DCQySr/8cLE2UiUVHo7qlrSatdLA9ETtgob3sJ4qTaBg5Lxg\n" 2277 + "SHy2gC+bvEpuIuRe64yXGuM/aP+ZvmIj9QBIVI9mJD8jLEOvQBBpAgMBAAE=\n" 2278 + "-----END RSA PUBLIC KEY-----\n"; 2279function TestConvertPemKeyBySync() { 2280 let asyKeyGenerator = cryptoFramework.createAsyKeyGenerator('RSA1024'); 2281 try { 2282 let keyPairData = asyKeyGenerator.convertPemKeySync(publicPkcs1Str1024, priKeyPkcs1Str1024); 2283 if (keyPairData != null) { 2284 console.info('[Sync]: convert pem key pair success'); 2285 } else { 2286 console.error("[Sync]: convert pem key pair result fail!"); 2287 } 2288 } catch (e) { 2289 console.error(`Sync error, ${e.code}, ${e.message}`); 2290 } 2291} 2292``` 2293 2294### convertPemKeySync<sup>18+</sup> 2295 2296convertPemKeySync(pubKey: string | null, priKey: string | null, password: string): KeyPair 2297 2298Converts data into an asymmetric key pair. This API returns the result synchronously. 2299 2300> **NOTE** 2301> The precautions for using **convertPemKeySync** are the same as those for [convertPemKey](#convertpemkey18). 2302 2303**Atomic service API**: This API can be used in atomic services since API version 18. 2304 2305**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 2306 2307**Parameters** 2308 2309| Name | Type | Mandatory| Description | 2310| ------ | -------- | ---- | ---------------- | 2311| pubKey | string \| null| Yes | Public key material to convert. If no public key is required, set this parameter to **null**.| 2312| priKey | string \| null| Yes | Private key material. If the private key does not need to be converted, you can pass in **null**. <br>**NOTE**: **pubKey** and **priKey** cannot be **null** at the same time.| 2313| password | string | Yes| Password used to decrypt the private key.| 2314 2315**Return value** 2316 2317| Type | Description | 2318| ----------------- | --------------------------------- | 2319| [KeyPair](#keypair) | Asymmetric key pair generated.| 2320 2321**Error codes** 2322For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 2323 2324| ID| Error Message | 2325| -------- | ---------------------- | 2326| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed. | 2327| 17620001 | memory operation failed. | 2328| 17630001 | crypto operation error. | 2329 2330**Example** 2331 2332```ts 2333import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 2334import { BusinessError } from '@kit.BasicServicesKit'; 2335 2336let priKeyPkcs1EncodingStr : string = 2337 "-----BEGIN RSA PRIVATE KEY-----\n" 2338 +"Proc-Type: 4,ENCRYPTED\n" 2339 +"DEK-Info: AES-128-CBC,815A066131BF05CF87CE610A59CC69AE\n\n" 2340 +"7Jd0vmOmYGFZ2yRY8fqRl3+6rQlFtNcMILvcb5KWHDSrxA0ULmJE7CW0DSRikHoA\n" 2341 +"t0KgafhYXeQXh0dRy9lvVRAFSLHCLJVjchx90V7ZSivBFEq7+iTozVp4AlbgYsJP\n" 2342 +"vx/1sfZD2WAcyMJ7IDmJyft7xnpVSXsyWGTT4f3eaHJIh1dqjwrso7ucAW0FK6rp\n" 2343 +"/TONyOoXNfXtRbVtxNyCWBxt4HCSclDZFvS9y8fz9ZwmCUV7jei/YdzyQI2wnE13\n" 2344 +"W8cKlpzRFL6BWi8XPrUtAw5MWeHBAPUgPWMfcmiaeyi5BJFhQCrHLi+Gj4EEJvp7\n" 2345 +"mP5cbnQAx6+paV5z9m71SKrI/WSc4ixsYYdVmlL/qwAK9YliFfoPl030YJWW6rFf\n" 2346 +"T7J9BUlHGUJ0RB2lURNNLakM+UZRkeE9TByzCzgTxuQtyv5Lwsh2mAk3ia5x0kUO\n" 2347 +"LHg3Eoabhdh+YZA5hHaxnpF7VjspB78E0F9Btq+A41rSJ6zDOdToHey4MJ2nxdey\n" 2348 +"Z3bi81TZ6Fp4IuROrvZ2B/Xl3uNKR7n+AHRKnaAO87ywzyltvjwSh2y3xhJueiRs\n" 2349 +"BiYkyL3/fnocD3pexTdN6h3JgQGgO5GV8zw/NrxA85mw8o9im0HreuFObmNj36T9\n" 2350 +"k5N+R/QIXW83cIQOLaWK1ThYcluytf0tDRiMoKqULiaA6HvDMigExLxuhCtnoF8I\n" 2351 +"iOLN1cPdEVQjzwDHLqXP2DbWW1z9iRepLZlEm1hLRLEmOrTGKezYupVv306SSa6J\n" 2352 +"OA55lAeXMbyjFaYCr54HWrpt4NwNBX1efMUURc+1LcHpzFrBTTLbfjIyq6as49pH\n" 2353 +"-----END RSA PRIVATE KEY-----\n" 2354function TestConvertPemKeyBySync() { 2355 let asyKeyGenerator = cryptoFramework.createAsyKeyGenerator('RSA1024'); 2356 try { 2357 let keyPairData = asyKeyGenerator.convertPemKeySync(null, priKeyPkcs1EncodingStr, "123456"); 2358 if (keyPairData != null) { 2359 console.info('[Sync]: convert pem key pair success'); 2360 } else { 2361 console.error("[Sync]: convert pem key pair result fail!"); 2362 } 2363 } catch (e) { 2364 console.error(`Sync error, ${e.code}, ${e.message}`); 2365 } 2366} 2367``` 2368 2369## cryptoFramework.createAsyKeyGeneratorBySpec<sup>10+</sup> 2370 2371createAsyKeyGeneratorBySpec(asyKeySpec: AsyKeySpec): AsyKeyGeneratorBySpec 2372 2373Obtains an asymmetric key generator instance with the specified key parameters. 2374 2375For details about the supported specifications, see [Asymmetric Key Generation and Conversion Specifications](../../security/CryptoArchitectureKit/crypto-asym-key-generation-conversion-spec.md). 2376 2377**Atomic service API**: This API can be used in atomic services since API version 12. 2378 2379**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 2380 2381The system capability is **SystemCapability.Security.CryptoFramework** in API versions 10 to 11, and **SystemCapability.Security.CryptoFramework.Key.AsymKey** since API version 12. 2382 2383**Parameters** 2384 2385| Name | Type | Mandatory| Description | 2386| ------- | ------ | ---- | -------------------------------- | 2387| asyKeySpec | [AsyKeySpec](#asykeyspec10) | Yes | Key parameters. The **AsyKeyGenerator** generates the public/private key based on the specified parameters.| 2388 2389**Return value** 2390 2391| Type | Description | 2392| ----------------------------------------------- | -------------------------- | 2393| [AsyKeyGeneratorBySpec](#asykeygeneratorbyspec10) | Returns the **AsyKeyGenerator** instance created.| 2394 2395**Error codes** 2396For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 2397 2398| ID| Error Message | 2399| -------- | ---------------------- | 2400| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 2401| 801 | this operation is not supported. | 2402| 17620001 | memory operation failed. | 2403 2404**Example** 2405 2406```ts 2407import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 2408 2409// Set the common parameters of the DSA1024 public and private keys. 2410function genDsa1024CommonSpecBigE() { 2411 let dsaCommonSpec: cryptoFramework.DSACommonParamsSpec = { 2412 algName: "DSA", 2413 specType: cryptoFramework.AsyKeySpecType.COMMON_PARAMS_SPEC, 2414 p: BigInt("0xed1501551b8ab3547f6355ffdc2913856ddeca198833dbd04f020e5f25e47c50e0b3894f7690a0d2ea5ed3a7be25c54292a698e1f086eb3a97deb4dbf04fcad2dafd94a9f35c3ae338ab35477e16981ded6a5b13d5ff20bf55f1b262303ad3a80af71aa6aa2354d20e9c82647664bdb6b333b7bea0a5f49d55ca40bc312a1729"), 2415 q: BigInt("0xd23304044019d5d382cfeabf351636c7ab219694ac845051f60b047b"), 2416 g: BigInt("0x2cc266d8bd33c3009bd67f285a257ba74f0c3a7e12b722864632a0ac3f2c17c91c2f3f67eb2d57071ef47aaa8f8e17a21ad2c1072ee1ce281362aad01dcbcd3876455cd17e1dd55d4ed36fa011db40f0bbb8cba01d066f392b5eaa9404bfcb775f2196a6bc20eeec3db32d54e94d87ecdb7a0310a5a017c5cdb8ac78597778bd"), 2417 } 2418 return dsaCommonSpec; 2419} 2420 2421// Set full parameters of the DSA1024 key pair. 2422function genDsa1024KeyPairSpecBigE() { 2423 let dsaCommonSpec = genDsa1024CommonSpecBigE(); 2424 let dsaKeyPairSpec: cryptoFramework.DSAKeyPairSpec = { 2425 algName: "DSA", 2426 specType: cryptoFramework.AsyKeySpecType.KEY_PAIR_SPEC, 2427 params: dsaCommonSpec, 2428 sk: BigInt("0xa2dd2adb2d11392c2541930f61f1165c370aabd2d78d00342e0a2fd9"), 2429 pk: BigInt("0xae6b5d5042e758f3fc9a02d009d896df115811a75b5f7b382d8526270dbb3c029403fafb8573ba4ef0314ea86f09d01e82a14d1ebb67b0c331f41049bd6b1842658b0592e706a5e4d20c14b67977e17df7bdd464cce14b5f13bae6607760fcdf394e0b73ac70aaf141fa4dafd736bd0364b1d6e6c0d7683a5de6b9221e7f2d6b"), 2430 } 2431 return dsaKeyPairSpec; 2432} 2433 2434let asyKeyPairSpec = genDsa1024KeyPairSpecBigE(); // The JS input must be a positive number in big-endian format. 2435let asyKeyGeneratorBySpec = cryptoFramework.createAsyKeyGeneratorBySpec(asyKeyPairSpec); 2436``` 2437 2438## AsyKeyGeneratorBySpec<sup>10+</sup> 2439 2440Provides APIs for using the **AsKeyGenerator**. Before using the APIs of this class, you need to use [createAsyKeyGeneratorBySpec()](#cryptoframeworkcreateasykeygeneratorbyspec10) to create an **AsyKeyGeneratorBySpec** instance. 2441 2442### Attributes 2443 2444**Atomic service API**: This API can be used in atomic services since API version 12. 2445 2446**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 2447 2448The system capability is **SystemCapability.Security.CryptoFramework** in API versions 10 to 11, and **SystemCapability.Security.CryptoFramework.Key.AsymKey** since API version 12. 2449 2450| Name | Type | Read-Only| Optional| Description | 2451| ------- | ------ | ---- | ---- | -------------------------- | 2452| algName | string | Yes | No | Algorithm used by the asymmetric key generator.| 2453 2454### generateKeyPair<sup>10+</sup> 2455 2456generateKeyPair(callback: AsyncCallback\<KeyPair>): void 2457 2458Generates an asymmetric key pair. This API uses an asynchronous callback to return the result. 2459 2460If 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. 2461 2462**Atomic service API**: This API can be used in atomic services since API version 12. 2463 2464**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 2465 2466The system capability is **SystemCapability.Security.CryptoFramework** in API versions 10 to 11, and **SystemCapability.Security.CryptoFramework.Key.AsymKey** since API version 12. 2467 2468**Parameters** 2469 2470| Name | Type | Mandatory| Description | 2471| -------- | ----------------------- | ---- | ------------------------------ | 2472| callback | AsyncCallback\<[KeyPair](#keypair)> | Yes | Callback used to return the key pair obtained.| 2473 2474**Error codes** 2475For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 2476 2477| ID| Error Message | 2478| -------- | ----------------------- | 2479| 401 | invalid parameters. Possible causes: <br>Incorrect parameter types; | 2480| 17620001 | memory operation failed. | 2481| 17630001 | crypto operation error. | 2482 2483**Example** 2484 2485<!--code_no_check--> 2486```ts 2487let asyKeyPairSpec: cryptoFramework.DSAKeyPairSpec; // Use DSA as an example. asyKeyPairSpec specifies full parameters of the private and public keys. The generation process is omitted here. 2488let asyKeyGeneratorBySpec = cryptoFramework.createAsyKeyGeneratorBySpec(asyKeyPairSpec); 2489asyKeyGeneratorBySpec.generateKeyPair((err, keyPair) => { 2490 if (err) { 2491 console.error("generateKeyPair: error."); 2492 return; 2493 } 2494 console.info('generateKeyPair: success.'); 2495}) 2496``` 2497 2498### generateKeyPair<sup>10+</sup> 2499 2500generateKeyPair(): Promise\<KeyPair> 2501 2502Generates an asymmetric key pair. This API uses a promise to return the result. 2503 2504If 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. 2505 2506**Atomic service API**: This API can be used in atomic services since API version 12. 2507 2508**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 2509 2510The system capability is **SystemCapability.Security.CryptoFramework** in API versions 10 to 11, and **SystemCapability.Security.CryptoFramework.Key.AsymKey** since API version 12. 2511 2512**Return value** 2513 2514| Type | Description | 2515| ----------------- | --------------------------------- | 2516| Promise\<[KeyPair](#keypair)> | Promise used to return the key pair generated.| 2517 2518**Error codes** 2519For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 2520 2521| ID| Error Message | 2522| -------- | ---------------------- | 2523| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed. | 2524| 17620001 | memory operation failed. | 2525| 17630001 | crypto operation error. | 2526 2527**Example** 2528 2529<!--code_no_check--> 2530```ts 2531import { BusinessError } from '@kit.BasicServicesKit'; 2532 2533let asyKeyPairSpec: cryptoFramework.DSAKeyPairSpec; // Use DSA as an example. asyKeyPairSpec specifies full parameters of the private and public keys. The generation process is omitted here. 2534let asyKeyGeneratorBySpec = cryptoFramework.createAsyKeyGeneratorBySpec(asyKeyPairSpec); 2535let keyGenPromise = asyKeyGeneratorBySpec.generateKeyPair(); 2536keyGenPromise.then(keyPair => { 2537 console.info('generateKeyPair success.'); 2538}).catch((error: BusinessError) => { 2539 console.error("generateKeyPair error."); 2540}); 2541``` 2542 2543### generateKeyPairSync<sup>12+</sup> 2544 2545generateKeyPairSync(): KeyPair 2546 2547Generates a public key using this asymmetric key generator. This API returns the result synchronously. 2548 2549If 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. 2550 2551**Atomic service API**: This API can be used in atomic services since API version 12. 2552 2553**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 2554 2555**Return value** 2556 2557| Type | Description | 2558| ----------------- | --------------------------------- | 2559| [KeyPair](#keypair) | Asymmetric key pair generated.| 2560 2561**Error codes** 2562For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 2563 2564| ID| Error Message | 2565| -------- | ---------------------- | 2566| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed. | 2567| 17620001 | memory operation failed. | 2568| 17630001 | crypto operation error. | 2569 2570**Example** 2571 2572<!--code_no_check--> 2573```ts 2574import { BusinessError } from '@kit.BasicServicesKit'; 2575 2576let asyKeyPairSpec: cryptoFramework.DSAKeyPairSpec; // Use DSA as an example. asyKeyPairSpec specifies full parameters of the private and public keys. The generation process is omitted here. 2577let asyKeyGeneratorBySpec = cryptoFramework.createAsyKeyGeneratorBySpec(asyKeyPairSpec); 2578try { 2579 let keyPairData = asyKeyGeneratorBySpec.generateKeyPairSync(); 2580 if (keyPairData != null) { 2581 console.info('[Sync]: key pair success'); 2582 } else { 2583 console.error("[Sync]: get key pair result fail!"); 2584 } 2585} catch (error) { 2586 let e: BusinessError = error as BusinessError; 2587 console.error(`sync error, ${e.code}, ${e.message}`); 2588} 2589``` 2590 2591### generatePriKey<sup>10+</sup> 2592 2593generatePriKey(callback: AsyncCallback\<PriKey>): void 2594 2595Generates an asymmetric key pair. This API uses an asynchronous callback to return the result. 2596 2597If [PRIVATE_KEY_SPEC](#asykeyspectype10) is used to create a key generator, the key generator generates the specified private key. If [KEY_PAIR_SPEC](#asykeyspectype10) is used to create a key generator, you can obtain the specified private key from the key pair generated. 2598 2599**Atomic service API**: This API can be used in atomic services since API version 12. 2600 2601**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 2602 2603The system capability is **SystemCapability.Security.CryptoFramework** in API versions 10 to 11, and **SystemCapability.Security.CryptoFramework.Key.AsymKey** since API version 12. 2604 2605**Parameters** 2606 2607| Name | Type | Mandatory| Description | 2608| -------- | ----------------------- | ---- | ------------------------------ | 2609| callback | AsyncCallback\<[PriKey](#prikey)> | Yes | Callback used to return the key pair obtained.| 2610 2611**Error codes** 2612For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 2613 2614| ID| Error Message | 2615| -------- | ---------------------- | 2616| 401 | invalid parameters. Possible causes: <br>Mandatory parameters are left unspecified; | 2617| 17620001 | memory operation failed. | 2618| 17630001 | crypto operation error. | 2619 2620**Example** 2621 2622<!--code_no_check--> 2623```ts 2624let asyKeyPairSpec: cryptoFramework.DSAKeyPairSpec; // Use DSA as an example. asyKeyPairSpec specifies full parameters of the private and public keys. The generation process is omitted here. 2625let asyKeyGeneratorBySpec = cryptoFramework.createAsyKeyGeneratorBySpec(asyKeyPairSpec); 2626asyKeyGeneratorBySpec.generatePriKey((err, prikey) => { 2627 if (err) { 2628 console.error("generatePriKey: error."); 2629 return; 2630 } 2631 console.info('generatePriKey: success.'); 2632}) 2633``` 2634 2635### generatePriKey<sup>10+</sup> 2636 2637generatePriKey(): Promise\<PriKey> 2638 2639Generates an asymmetric key pair. This API uses a promise to return the result. 2640 2641If 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. 2642 2643**Atomic service API**: This API can be used in atomic services since API version 12. 2644 2645**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 2646 2647The system capability is **SystemCapability.Security.CryptoFramework** in API versions 10 to 11, and **SystemCapability.Security.CryptoFramework.Key.AsymKey** since API version 12. 2648 2649**Return value** 2650 2651| Type | Description | 2652| ----------------- | --------------------------------- | 2653| Promise\<[PriKey](#prikey)> | Promise used to return the key pair generated.| 2654 2655**Error codes** 2656For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 2657 2658| ID| Error Message | 2659| -------- | ---------------------- | 2660| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed. | 2661| 17620001 | memory operation failed. | 2662| 17630001 | crypto operation error. | 2663 2664**Example** 2665 2666<!--code_no_check--> 2667```ts 2668import { BusinessError } from '@kit.BasicServicesKit'; 2669 2670let asyKeyPairSpec: cryptoFramework.DSAKeyPairSpec; // Use DSA as an example. asyKeyPairSpec specifies full parameters of the private and public keys. The generation process is omitted here. 2671let asyKeyGeneratorBySpec = cryptoFramework.createAsyKeyGeneratorBySpec(asyKeyPairSpec); 2672let keyGenPromise = asyKeyGeneratorBySpec.generatePriKey(); 2673keyGenPromise.then(priKey => { 2674 console.info('generatePriKey success.'); 2675}).catch((error: BusinessError) => { 2676 console.error("generatePriKey error."); 2677}); 2678``` 2679 2680### generatePriKeySync<sup>12+</sup> 2681 2682generatePriKeySync(): PriKey 2683 2684Generates a public key using this asymmetric key generator. This API returns the result synchronously. 2685 2686If 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. 2687 2688**Atomic service API**: This API can be used in atomic services since API version 12. 2689 2690**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 2691 2692**Return value** 2693 2694| Type | Description | 2695| ----------------- | --------------------------------- | 2696| [PriKey](#prikey) | Asymmetric key pair generated.| 2697 2698**Error codes** 2699For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 2700 2701| ID| Error Message | 2702| -------- | ---------------------- | 2703| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed. | 2704| 17620001 | memory operation failed. | 2705| 17630001 | crypto operation error. | 2706 2707**Example** 2708 2709<!--code_no_check--> 2710```ts 2711let asyKeyPairSpec: cryptoFramework.DSAKeyPairSpec; // Use DSA as an example. asyKeyPairSpec specifies full parameters of the private and public keys. The generation process is omitted here. 2712let asyKeyGeneratorBySpec = cryptoFramework.createAsyKeyGeneratorBySpec(asyKeyPairSpec); 2713try { 2714 let priKeyData = asyKeyGeneratorBySpec.generatePriKeySync(); 2715 if (priKeyData != null) { 2716 console.info('[Sync]: pri key success'); 2717 } else { 2718 console.error("[Sync]: get pri key result fail!"); 2719 } 2720} catch (e) { 2721 console.error(`sync error, ${e.code}, ${e.message}`); 2722} 2723``` 2724 2725### generatePubKey<sup>10+</sup> 2726 2727generatePubKey(callback: AsyncCallback\<PubKey>): void 2728 2729Generates an asymmetric key pair. This API uses an asynchronous callback to return the result. 2730 2731If 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. 2732 2733**Atomic service API**: This API can be used in atomic services since API version 12. 2734 2735**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 2736 2737The system capability is **SystemCapability.Security.CryptoFramework** in API versions 10 to 11, and **SystemCapability.Security.CryptoFramework.Key.AsymKey** since API version 12. 2738 2739**Parameters** 2740 2741| Name | Type | Mandatory| Description | 2742| -------- | ----------------------- | ---- | ------------------------------ | 2743| callback | AsyncCallback\<[PubKey](#pubkey)> | Yes | Callback used to return the key pair obtained.| 2744 2745**Error codes** 2746For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 2747 2748| ID| Error Message | 2749| -------- | ---------------------- | 2750| 401 | invalid parameters. Possible causes:<br> Incorrect parameter types; | 2751| 17620001 | memory operation failed. | 2752| 17630001 | crypto operation error. | 2753 2754**Example** 2755 2756<!--code_no_check--> 2757```ts 2758let asyKeyPairSpec: cryptoFramework.DSAKeyPairSpec; // Use DSA as an example. asyKeyPairSpec specifies full parameters of the private and public keys. The generation process is omitted here. 2759let asyKeyGeneratorBySpec = cryptoFramework.createAsyKeyGeneratorBySpec(asyKeyPairSpec); 2760asyKeyGeneratorBySpec.generatePubKey((err, pubKey) => { 2761 if (err) { 2762 console.error("generatePubKey: error."); 2763 return; 2764 } 2765 console.info('generatePubKey: success.'); 2766}) 2767``` 2768 2769### generatePubKey<sup>10+</sup> 2770 2771generatePubKey(): Promise\<PubKey> 2772 2773Generates an asymmetric key pair. This API uses a promise to return the result. 2774 2775If 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. 2776 2777**Atomic service API**: This API can be used in atomic services since API version 12. 2778 2779**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 2780 2781The system capability is **SystemCapability.Security.CryptoFramework** in API versions 10 to 11, and **SystemCapability.Security.CryptoFramework.Key.AsymKey** since API version 12. 2782 2783**Return value** 2784 2785| Type | Description | 2786| ----------------- | --------------------------------- | 2787| Promise\<[PubKey](#pubkey)> | Promise used to return the key pair generated.| 2788 2789**Error codes** 2790For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 2791 2792| ID| Error Message | 2793| -------- | ---------------------- | 2794| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed. | 2795| 17620001 | memory operation failed. | 2796| 17630001 | crypto operation error. | 2797 2798**Example** 2799 2800<!--code_no_check--> 2801```ts 2802import { BusinessError } from '@kit.BasicServicesKit'; 2803 2804let asyKeyPairSpec: cryptoFramework.DSAKeyPairSpec; // Use DSA as an example. asyKeyPairSpec specifies full parameters of the private and public keys. The generation process is omitted here. 2805let asyKeyGeneratorBySpec = cryptoFramework.createAsyKeyGeneratorBySpec(asyKeyPairSpec); 2806let keyGenPromise = asyKeyGeneratorBySpec.generatePubKey(); 2807keyGenPromise.then(pubKey => { 2808 console.info('generatePubKey success.'); 2809}).catch((error: BusinessError) => { 2810 console.error("generatePubKey error."); 2811}); 2812``` 2813 2814### generatePubKeySync<sup>12+</sup> 2815 2816generatePubKeySync(): PubKey 2817 2818Generates a public key using this asymmetric key generator. This API returns the result synchronously. 2819 2820If [PUBLIC_KEY_SPEC](#asykeyspectype10) is used to create a key generator, the key generator generates the specified public key. If [KEY_PAIR_SPEC](#asykeyspectype10) is used to create a key generator, you can obtain the specified public key from the key pair generated. 2821 2822**Atomic service API**: This API can be used in atomic services since API version 12. 2823 2824**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 2825 2826**Return value** 2827 2828| Type | Description | 2829| ----------------- | --------------------------------- | 2830| [PubKey](#pubkey) | Asymmetric key pair generated.| 2831 2832**Error codes** 2833For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 2834 2835| ID| Error Message | 2836| -------- | ---------------------- | 2837| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed. | 2838| 17620001 | memory operation failed. | 2839| 17630001 | crypto operation error. | 2840 2841**Example** 2842 2843<!--code_no_check--> 2844```ts 2845let asyKeyPairSpec: cryptoFramework.DSAKeyPairSpec; // Use DSA as an example. asyKeyPairSpec specifies full parameters of the private and public keys. The generation process is omitted here. 2846let asyKeyGeneratorBySpec = cryptoFramework.createAsyKeyGeneratorBySpec(asyKeyPairSpec); 2847try { 2848 let pubKeyData = asyKeyGeneratorBySpec.generatePubKeySync(); 2849 if (pubKeyData != null) { 2850 console.info('[Sync]: pub key success'); 2851 } else { 2852 console.error("[Sync]: get pub key result fail!"); 2853 } 2854} catch (e) { 2855 console.error(`sync error, ${e.code}, ${e.message}`); 2856} 2857``` 2858 2859## ECCKeyUtil<sup>11+</sup> 2860 2861Provides APIs for generating common parameters for an asymmetric key pair based on the elliptic curve name. 2862 2863### genECCCommonParamsSpec<sup>11+</sup> 2864 2865static genECCCommonParamsSpec(curveName: string): ECCCommonParamsSpec 2866 2867Generates 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). 2868 2869**Atomic service API**: This API can be used in atomic services since API version 12. 2870 2871**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 2872 2873The system capability is **SystemCapability.Security.CryptoFramework** in API version 11, and **SystemCapability.Security.CryptoFramework.Key.AsymKey** since API version 12. 2874 2875**Parameters** 2876 2877| Name | Type | Mandatory| Description | 2878| ------- | ------ | ---- | ---------------------------------------------- | 2879| curveName | string | Yes | NID of the elliptic curve.| 2880 2881**Return value** 2882 2883| Type | Description | 2884| ----------------- | --------------------------------- | 2885| [ECCCommonParamsSpec](#ecccommonparamsspec10) | ECC common parameters generated.| 2886 2887**Error codes** 2888For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 2889 2890| ID| Error Message | 2891| -------- | -------------------------------- | 2892| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 2893| 801 | this operation is not supported. | 2894| 17620001 | memory operation failed. | 2895 2896**Example** 2897 2898```ts 2899import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 2900import { BusinessError } from '@kit.BasicServicesKit'; 2901try { 2902 let ECCCommonParamsSpec = cryptoFramework.ECCKeyUtil.genECCCommonParamsSpec('NID_brainpoolP160r1'); 2903 console.info('genECCCommonParamsSpec success'); 2904} catch (err) { 2905 let e: BusinessError = err as BusinessError; 2906 console.error(`genECCCommonParamsSpec error, ${e.code}, ${e.message}`); 2907} 2908``` 2909 2910### convertPoint<sup>12+</sup> 2911 2912static convertPoint(curveName: string, encodedPoint: Uint8Array): Point 2913 2914Converts the specified point data into a **Point** object based on the curve name (NID). Currently, compressed and uncompressed point data is supported. 2915 2916> **NOTE** 2917> 2918> According to section 2.2 in RFC 5480:<br> 2919> 1. The uncompressed point data is represented as **0x04**\|x coordinate\|y coordinate. 2920> 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). 2921 2922**Atomic service API**: This API can be used in atomic services since API version 12. 2923 2924**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 2925 2926**Parameters** 2927 2928| Name | Type | Mandatory| Description | 2929| ------------ | ---------- | ---- | ---------------------------------------------- | 2930| curveName | string | Yes | Elliptic curve name, that is, the NID.| 2931| encodedPoint | Uint8Array | Yes | Data of the point on the ECC elliptic curve to convert.| 2932 2933**Return value** 2934 2935| Type | Description | 2936| ----------------- | ------------------- | 2937| [Point](#point10) | **Point** object obtained.| 2938 2939**Error codes** 2940For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 2941 2942| ID| Error Message | 2943| -------- | ---------------------- | 2944| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 2945| 17620001 | memory operation failed. | 2946| 17630001 | crypto operation error. | 2947 2948**Example** 2949 2950```ts 2951import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 2952 2953// Randomly generated uncompressed point data. 2954let 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]); 2955let returnPoint = cryptoFramework.ECCKeyUtil.convertPoint('NID_brainpoolP256r1', pkData); 2956console.info('returnPoint: ' + returnPoint.x.toString(16)); 2957``` 2958 2959### getEncodedPoint<sup>12+</sup> 2960 2961static getEncodedPoint(curveName: string, point: Point, format: string): Uint8Array 2962 2963Obtains the point data in the specified format from a **Point** object. Currently, compressed and uncompressed point data is supported. 2964 2965**Atomic service API**: This API can be used in atomic services since API version 12. 2966 2967**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 2968 2969**Parameters** 2970 2971| Name | Type | Mandatory| Description | 2972| ------------ | ----------------- | ---- | ---------------------------------------------- | 2973| curveName | string | Yes | Elliptic curve name, that is, the NID.| 2974| point | [Point](#point10) | Yes | **Point** object of the elliptic curve.| 2975| format | string | Yes | Format of the point data to obtain. Currently, the value can be **COMPRESSED** or **UNCOMPRESSED** only.| 2976 2977**Return value** 2978 2979| Type | Description | 2980| ----------------- | --------------------------------- | 2981| Uint8Array | Point data in the specified format.| 2982 2983**Error codes** 2984For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 2985 2986| ID| Error Message | 2987| -------- | ---------------------- | 2988| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 2989| 17620001 | memory operation failed. | 2990| 17630001 | crypto operation error. | 2991 2992**Example** 2993 2994```ts 2995import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 2996 2997async function doTest() { 2998 let generator = cryptoFramework.createAsyKeyGenerator('ECC_BrainPoolP256r1'); 2999 let keyPair = await generator.generateKeyPair(); 3000 let eccPkX = keyPair.pubKey.getAsyKeySpec(cryptoFramework.AsyKeySpecItem.ECC_PK_X_BN); 3001 let eccPkY = keyPair.pubKey.getAsyKeySpec(cryptoFramework.AsyKeySpecItem.ECC_PK_Y_BN); 3002 console.info('ECC_PK_X_BN 16: ' + eccPkX.toString(16)); 3003 console.info('ECC_PK_Y_BN 16: ' + eccPkY.toString(16)); 3004 // Place eccPkX.toString(16) in x and eccPkY.toString(16) in y. 3005 let returnPoint: cryptoFramework.Point = { 3006 x: BigInt('0x' + eccPkX.toString(16)), 3007 y: BigInt('0x' + eccPkY.toString(16)) 3008 }; 3009 let returnData = cryptoFramework.ECCKeyUtil.getEncodedPoint('NID_brainpoolP256r1', returnPoint, 'UNCOMPRESSED'); 3010 console.info('returnData: ' + returnData); 3011} 3012``` 3013 3014## DHKeyUtil<sup>11+</sup> 3015 3016Generates common parameters for a DH key based on the prime **p** length and the private key length. 3017 3018### genDHCommonParamsSpec<sup>11+</sup> 3019 3020static genDHCommonParamsSpec(pLen: number, skLen?: number): DHCommonParamsSpec 3021 3022Generates 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). 3023 3024**Atomic service API**: This API can be used in atomic services since API version 12. 3025 3026**System capability**: SystemCapability.Security.CryptoFramework.Key.AsymKey 3027 3028The system capability is **SystemCapability.Security.CryptoFramework** in API version 11, and **SystemCapability.Security.CryptoFramework.Key.AsymKey** since API version 12. 3029 3030**Parameters** 3031 3032| Name| Type | Mandatory| Description | 3033| ------ | ------ | ---- | ------------------------------------------------ | 3034| pLen | number | Yes | Length of the prime **p**, in bits.| 3035| skLen | number | No | Length of the private key, in bits. | 3036 3037**Return value** 3038 3039| Type | Description | 3040| ----------------- | --------------------------------- | 3041| [DHCommonParamsSpec](#dhcommonparamsspec11) | DH common parameters generated.| 3042 3043**Error codes** 3044For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 3045 3046| ID| Error Message | 3047| -------- | -------------------------------- | 3048| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 3049| 801 | this operation is not supported. | 3050| 17620001 | memory operation failed. | 3051| 17630001 | crypto operation error. | 3052 3053**Example** 3054 3055```ts 3056import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 3057import { BusinessError } from '@kit.BasicServicesKit'; 3058try { 3059 let DHCommonParamsSpec = cryptoFramework.DHKeyUtil.genDHCommonParamsSpec(2048); 3060 console.info('genDHCommonParamsSpec success'); 3061} catch (err) { 3062 let e: BusinessError = err as BusinessError; 3063 console.error(`genDHCommonParamsSpec error, ${e.code}, ${e.message}`); 3064} 3065``` 3066 3067## SM2CryptoUtil<sup>12+</sup> 3068 3069Provides APIs for SM2 cryptographic operations. 3070 3071### genCipherTextBySpec<sup>12+</sup> 3072 3073static genCipherTextBySpec(spec: SM2CipherTextSpec, mode?: string): DataBlob 3074 3075Generates SM2 ciphertext in ASN.1 format. 3076 3077**Atomic service API**: This API can be used in atomic services since API version 12. 3078 3079**System capability**: SystemCapability.Security.CryptoFramework.Cipher 3080 3081**Parameters** 3082 3083| Name| Type | Mandatory| Description | 3084| ------ | ------ | ---- | ------------------------------------------------ | 3085| spec | [SM2CipherTextSpec](#sm2ciphertextspec12) | Yes | SM2 ciphertext parameters.| 3086| mode | string | No | Order of the SM2 parameters in the ciphertext. Currently, only C1C3C2 is supported. | 3087 3088**Return value** 3089 3090| Type | Description | 3091| ----------------- | --------------------------------- | 3092| [DataBlob](#datablob) | SM2 ciphertext in ASN.1 format.| 3093 3094**Error codes** 3095For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 3096 3097| ID| Error Message | 3098| -------- | -------------------------------- | 3099| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 3100| 17620001 | memory operation failed. | 3101| 17630001 | crypto operation error. | 3102 3103**Example** 3104 3105```ts 3106import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 3107import { BusinessError } from '@kit.BasicServicesKit'; 3108try { 3109 let spec : cryptoFramework.SM2CipherTextSpec = { 3110 xCoordinate: BigInt('20625015362595980457695435345498579729138244358573902431560627260141789922999'), 3111 yCoordinate: BigInt('48563164792857017065725892921053777369510340820930241057309844352421738767712'), 3112 cipherTextData: new Uint8Array([100,227,78,195,249,179,43,70,242,69,169,10,65,123]), 3113 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]), 3114 } 3115 let data = cryptoFramework.SM2CryptoUtil.genCipherTextBySpec(spec, 'C1C3C2'); 3116 console.info('genCipherTextBySpec success'); 3117} catch (err) { 3118 let e: BusinessError = err as BusinessError; 3119 console.error(`genCipherTextBySpec error, ${e.code}, ${e.message}`); 3120} 3121``` 3122 3123### getCipherTextSpec<sup>12+</sup> 3124 3125static getCipherTextSpec(cipherText: DataBlob, mode?: string): SM2CipherTextSpec 3126 3127Obtains SM2 ciphertext parameters from the SM2 ciphertext in ASN.1 format. 3128 3129**Atomic service API**: This API can be used in atomic services since API version 12. 3130 3131**System capability**: SystemCapability.Security.CryptoFramework.Cipher 3132 3133**Parameters** 3134 3135| Name| Type | Mandatory| Description | 3136| ------ | ------ | ---- | ------------------------------------------------ | 3137| cipherText | [DataBlob](#datablob) | Yes | SM2 ciphertext in ASN.1 format. 3138| mode | string | No | Order of the SM2 parameters in the ciphertext. Currently, only C1C3C2 is supported. | 3139 3140**Return value** 3141 3142| Type | Description | 3143| ----------------- | --------------------------------- | 3144| [SM2CipherTextSpec](#sm2ciphertextspec12) | SM2 ciphertext parameters obtained.| 3145 3146**Error codes** 3147For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 3148 3149| ID| Error Message | 3150| -------- | -------------------------------- | 3151| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 3152| 17620001 | memory operation failed. | 3153| 17630001 | crypto operation error. | 3154 3155```ts 3156import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 3157import { BusinessError } from '@kit.BasicServicesKit'; 3158try { 3159 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]); 3160 let cipherText : cryptoFramework.DataBlob = {data : cipherTextArray}; 3161 let spec : cryptoFramework.SM2CipherTextSpec = cryptoFramework.SM2CryptoUtil.getCipherTextSpec(cipherText, 'C1C3C2'); 3162 console.info('getCipherTextSpec success'); 3163} catch (err) { 3164 let e: BusinessError = err as BusinessError; 3165 console.error(`getCipherTextSpec error, ${e.code}, ${e.message}`); 3166} 3167``` 3168 3169## cryptoFramework.createCipher 3170 3171createCipher(transformation: string): Cipher 3172 3173Creates a [Cipher](#cipher) instance based on the specified algorithm. 3174 3175For 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). 3176 3177**Atomic service API**: This API can be used in atomic services since API version 12. 3178 3179**System capability**: SystemCapability.Security.CryptoFramework.Cipher 3180 3181The system capability is **SystemCapability.Security.CryptoFramework** in API versions 9 to 11, and **SystemCapability.Security.CryptoFramework.Cipher** since API version 12. 3182 3183**Parameters** 3184 3185| Name | Type | Mandatory| Description | 3186| -------------- | ------ | ---- | ------------------------------------------------------------ | 3187| transformation | string | Yes | Combination of the algorithm name (including the key length), encryption mode, and padding algorithm of the **Cipher** instance to create.| 3188 3189> **NOTE** 3190> 3191> 1. In symmetric encryption and decryption, PKCS #5 and PKCS #7 share the same implementation, with padding length and block size remaining consistent. In 3DES, padding is applied in 8-byte blocks; in AES, padding is applied in 16-byte blocks. **NoPadding** means no padding is applied. 3192> <br>You need to understand the differences between different block cipher modes and use the correct parameter specifications. For example, padding is required for ECB and CBC. Otherwise, ensure that the plaintext length is an integer multiple of the block size. No padding is recommended for other modes. In this case, the ciphertext length is the same as the plaintext length. 3193> 2. When RSA or SM2 is used for asymmetric encryption and decryption, two **Cipher** objects must be created to perform encryption and decryption separately. This is not required for symmetric encryption and decryption. If the algorithm specifications are the same, the same **Cipher** object can be used for encryption and decryption. 3194 3195**Return value** 3196 3197| Type | Description | 3198| ----------------- | ------------------------ | 3199| [Cipher](#cipher) | [Cipher](#cipher) instance created.| 3200 3201**Error codes** 3202For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 3203 3204| ID| Error Message | 3205| -------- | ---------------------- | 3206| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 3207| 801 | this operation is not supported. | 3208| 17620001 | memory operation failed. | 3209 3210**Example** 3211 3212```ts 3213import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 3214import { BusinessError } from '@kit.BasicServicesKit'; 3215 3216let cipherAlgName = '3DES192|ECB|PKCS7'; 3217try { 3218 let cipher = cryptoFramework.createCipher(cipherAlgName); 3219 console.info('cipher algName: ' + cipher.algName); 3220} catch (error) { 3221 let e: BusinessError = error as BusinessError; 3222 console.error(`sync error, ${e.code}, ${e.message}`); 3223} 3224``` 3225 3226## Cipher 3227 3228Provides 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. 3229 3230For details about the encryption and decryption process, see [Encryption and Decryption Overview] (../../security/CryptoArchitectureKit/crypto-encryption-decryption-overview.md). 3231 3232A complete symmetric encryption/decryption process is slightly different from the asymmetric encryption/decryption process. 3233 3234- 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. 3235- 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. 3236 3237### Attributes 3238 3239**Atomic service API**: This API can be used in atomic services since API version 12. 3240 3241**System capability**: SystemCapability.Security.CryptoFramework.Cipher 3242 3243The system capability is **SystemCapability.Security.CryptoFramework** in API versions 9 to 11, and **SystemCapability.Security.CryptoFramework.Cipher** since API version 12. 3244 3245| Name | Type | Read-Only| Optional| Description | 3246| ------- | ------ | ---- | ---- | ---------------------------- | 3247| algName | string | Yes | No | Algorithm.| 3248 3249### init 3250 3251init(opMode: CryptoMode, key: Key, params: ParamsSpec | null, callback: AsyncCallback\<void>): void 3252 3253Initializes a [cipher](#cipher) instance. This API returns the result synchronously. **init**, **update**, and **doFinal** must be used together. **init** and **doFinal** are mandatory, and **update** is optional. 3254 3255This API can be used only after a [Cipher](#cipher) instance is created by using [createCipher](#cryptoframeworkcreatecipher). 3256 3257**Atomic service API**: This API can be used in atomic services since API version 12. 3258 3259**System capability**: SystemCapability.Security.CryptoFramework.Cipher 3260 3261The system capability is **SystemCapability.Security.CryptoFramework** in API versions 9 to 11, and **SystemCapability.Security.CryptoFramework.Cipher** since API version 12. 3262 3263**Parameters** 3264 3265| Name | Type | Mandatory| Description | 3266| -------- | ------------------------- | ---- | ------------------------------------------------------------ | 3267| opMode | [CryptoMode](#cryptomode) | Yes | Operation (encryption or decryption) to perform. | 3268| key | [Key](#key) | Yes | Key for encryption or decryption. | 3269| 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.| 3270| callback | AsyncCallback\<void> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object. | 3271 3272**Error codes** 3273For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 3274 3275| ID| Error Message | 3276| -------- | --------------------------------------------------------- | 3277| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 3278| 17620001 | memory operation failed. | 3279| 17620002 | failed to convert parameters between arkts and c. | 3280| 17630001 | crypto operation error.| 3281 3282### init 3283 3284init(opMode: CryptoMode, key: Key, params: ParamsSpec | null): Promise\<void> 3285 3286Initializes 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. 3287 3288This API can be used only after a [Cipher](#cipher) instance is created by using [createCipher](#cryptoframeworkcreatecipher). 3289 3290**Atomic service API**: This API can be used in atomic services since API version 12. 3291 3292**System capability**: SystemCapability.Security.CryptoFramework.Cipher 3293 3294The system capability is **SystemCapability.Security.CryptoFramework** in API versions 9 to 11, and **SystemCapability.Security.CryptoFramework.Cipher** since API version 12. 3295 3296**Parameters** 3297 3298| Name | Type | Mandatory| Description | 3299| ------ | ------------------------- | ---- | ------------------------------------------------------------ | 3300| opMode | [CryptoMode](#cryptomode) | Yes | Operation (encryption or decryption) to perform. | 3301| key | [Key](#key) | Yes | Key for encryption or decryption. | 3302| 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. Before API version 10, only **ParamsSpec** is supported. Since API version 10, **null** is also supported.| 3303 3304**Return value** 3305 3306| Type | Description | 3307| -------------- | -------------------------------------- | 3308| Promise\<void> | Promise that returns no value.| 3309 3310**Error codes** 3311For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 3312 3313| ID| Error Message | 3314| -------- | ------------------------------------------------- | 3315| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 3316| 17620001 | memory operation failed. | 3317| 17620002 | failed to convert parameters between arkts and c. | 3318| 17630001 | crypto operation error.| 3319 3320### initSync<sup>12+</sup> 3321 3322initSync(opMode: CryptoMode, key: Key, params: ParamsSpec | null): void 3323 3324Initializes 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. 3325 3326This API can be used only after a [Cipher](#cipher) instance is created by using [createCipher](#cryptoframeworkcreatecipher). 3327 3328**Atomic service API**: This API can be used in atomic services since API version 12. 3329 3330**System capability**: SystemCapability.Security.CryptoFramework.Cipher 3331 3332**Parameters** 3333 3334| Name| Type | Mandatory| Description | 3335| ------ | ----------------------------------------------- | ---- | ------------------------------------------------------------ | 3336| opMode | [CryptoMode](#cryptomode) | Yes | Operation (encryption or decryption) to perform. | 3337| key | [Key](#key) | Yes | Key for encryption or decryption. | 3338| params | [ParamsSpec](#paramsspec) \| null| Yes | Parameters for encryption or decryption. For algorithm modes without parameters (such as ECB), **null** can be passed in.| 3339 3340**Error codes** 3341For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 3342 3343| ID| Error Message | 3344| -------- | ----------------------- | 3345| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 3346| 17620001 | memory operation failed. | 3347| 17620002 | failed to convert parameters between arkts and c. | 3348| 17630001 | crypto operation error. | 3349 3350### update 3351 3352update(data: DataBlob, callback: AsyncCallback\<DataBlob>): void 3353 3354Updates the data to encrypt or decrypt by segment. This API uses an asynchronous callback to return the encrypted or decrypted data. 3355 3356This API can be called only after the [Cipher](#cipher) instance is initialized by using [init()](#init-1). 3357 3358> **NOTE** 3359> 3360> 1. The results of **update()** and **doFinal()** may vary with the block mode used. If you are not familiar with the block modes, you are advised to check each **update()** and **doFinal()** result to ensure that the results are not **null**. When a valid result is returned, extract and concatenate the data to form a complete ciphertext or plaintext. 3361> 3362> For example, in ECB and CBC modes, encryption and decryption are performed by block regardless of whether the data input by **update()** is an integer multiple of the block size, and **update()** returns the newly processed block data. 3363> 3364> 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()** or **doFinal()**. 3365> 3366> In the final **doFinal()** operation, the remaining unprocessed data is padded based on the padding mode set in [createCipher](#cryptoframeworkcreatecipher) to the integer multiple of the block size to produce the final encrypted or decrypted data. 3367> 3368> For block cipher modes that can be converted to stream mode, the ciphertext length may be the same as the plaintext length. 3369> 3370> 2. You can call **update()** multiple times or skip calling **update()** (call **doFinal()** directly after **init()**), depending on the data volume. 3371> 3372> 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 pass data in multiple **update()** calls rather than processing it all at once. 3373> 3374> For details about the sample code for passing data in multiple **update()** calls, see [Encryption and Decryption by Segment with an AES Symmetric Key (GCM Mode)](../../security/CryptoArchitectureKit/crypto-aes-sym-encrypt-decrypt-gcm-by-segment.md). 3375> 3. RSA or SM2 asymmetric encryption and decryption do not support **update()**. 3376> 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. 3377 3378**Atomic service API**: This API can be used in atomic services since API version 12. 3379 3380**System capability**: SystemCapability.Security.CryptoFramework.Cipher 3381 3382The system capability is **SystemCapability.Security.CryptoFramework** in API versions 9 to 11, and **SystemCapability.Security.CryptoFramework.Cipher** since API version 12. 3383 3384**Parameters** 3385 3386| Name | Type | Mandatory| Description | 3387| -------- | ------------------------------------- | ---- | ------------------------------------------------------------ | 3388| data | [DataBlob](#datablob) | Yes | Data to be encrypted or decrypted. It cannot be null. | 3389| callback | AsyncCallback\<[DataBlob](#datablob)> | Yes | Callback used to return the result. If the data is updated successfully, **err** is **undefined** and **data** is **DataBlob**. Otherwise, **err** is an error object.| 3390 3391**Error codes** 3392For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 3393 3394| ID| Error Message | 3395| -------- | ------------------------------------------- | 3396| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 3397| 17620001 | memory operation failed. | 3398| 17620002 | failed to convert parameters between arkts and c. | 3399| 17630001 | crypto operation error. | 3400 3401### update 3402 3403update(data: DataBlob): Promise\<DataBlob> 3404 3405Updates the data to encrypt or decrypt by segment. This API uses a promise to return the encrypted or decrypted data. 3406 3407This API can be called only after the [Cipher](#cipher) instance is initialized by using [init()](#init-1). 3408 3409> **NOTE** 3410> 3411> 1. The results of **update()** and **doFinal()** may vary with the block mode used. If you are not familiar with the block modes, you are advised to check each update() and doFinal() result to ensure that the results are not null. When a valid result is returned, extract and concatenate the data to form a complete ciphertext or plaintext. 3412> <br>For example, in ECB and CBC modes, encryption and decryption are performed by block regardless of whether the data input by **update()** is an integer multiple of the block size, and **update()** returns the newly processed block data.<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()** or **doFinal()**.<br>In the final **doFinal()** operation, the remaining unprocessed data is padded based on the padding mode set in [createCipher](#cryptoframeworkcreatecipher) to the integer multiple of the block size to produce the final encrypted or decrypted data.<br>For block cipher modes that can be converted to stream mode, the ciphertext length may be the same as the plaintext length. 3413> 2. You can call **update()** multiple times or skip calling **update()** (call **doFinal()** directly after **init()**), depending on the data volume.<br> 3414> 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 pass data in multiple **update()** calls rather than processing it all at once.<br> 3415> For details about the sample code for passing data in multiple **update()** calls, see [Encryption and Decryption by Segment with an AES Symmetric Key (GCM Mode)](../../security/CryptoArchitectureKit/crypto-aes-sym-encrypt-decrypt-gcm-by-segment.md). 3416> 3. RSA or SM2 asymmetric encryption and decryption do not support **update()**. 3417> 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. 3418 3419**Atomic service API**: This API can be used in atomic services since API version 12. 3420 3421**System capability**: SystemCapability.Security.CryptoFramework.Cipher 3422 3423The system capability is **SystemCapability.Security.CryptoFramework** in API versions 9 to 11, and **SystemCapability.Security.CryptoFramework.Cipher** since API version 12. 3424 3425**Parameters** 3426 3427| Name| Type | Mandatory| Description | 3428| ---- | --------------------- | ---- | -------------------- | 3429| data | [DataBlob](#datablob) | Yes | Data to encrypt or decrypt. It cannot be null.| 3430 3431**Return value** 3432 3433| Type | Description | 3434| ------------------------------- | ------------------------------------------------ | 3435| Promise\<[DataBlob](#datablob)> | Promise used to return the **DataBlob** (containing the encrypted or decrypted data).| 3436 3437**Error codes** 3438For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 3439 3440| ID| Error Message | 3441| -------- | -------------------------------------------- | 3442| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 3443| 17620001 | memory operation failed. | 3444| 17620002 | failed to convert parameters between arkts and c. | 3445| 17630001 | crypto operation error. | 3446 3447### updateSync<sup>12+</sup> 3448 3449updateSync(data: DataBlob): DataBlob 3450 3451Updates the data to encrypt or decrypt by segment. This API uses an asynchronous callback to return the encrypted or decrypted data. 3452 3453This API can be called only after the [Cipher](#cipher) instance is initialized by using [initSync()](#initsync12). 3454 3455See **NOTE** in **update()** for other precautions. 3456 3457**Atomic service API**: This API can be used in atomic services since API version 12. 3458 3459**System capability**: SystemCapability.Security.CryptoFramework.Cipher 3460 3461**Parameters** 3462 3463| Name| Type | Mandatory| Description | 3464| ------ | --------------------- | ---- | ------------------------------------------------------------ | 3465| data | [DataBlob](#datablob) | Yes | Data to encrypt or decrypt. It cannot be null.| 3466 3467**Return value** 3468 3469| Type | Description | 3470| ------------------------------- | ------------------------------------------------ | 3471| [DataBlob](#datablob) | Encryption/decryption result.| 3472 3473**Error codes** 3474For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 3475 3476| ID| Error Message | 3477| -------- | ----------------------- | 3478| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 3479| 17620001 | memory operation failed. | 3480| 17620002 | failed to convert parameters between arkts and c. | 3481| 17630001 | crypto operation error. | 3482 3483### doFinal 3484 3485doFinal(data: DataBlob | null, callback: AsyncCallback\<DataBlob>): void 3486 3487(1) Processes the remaining data and the data passed in this time, and completes the encryption or decryption operation for symmetric encryption and decryption. This API uses an asynchronous callback to return the encrypted or decrypted data. If a small amount of data needs to be encrypted or decrypted, you can use **doFinal()** to pass in all the data without using **update()**. If all the data has been passed in by [update()](#update), you can pass in **null** in **data** of **doFinal()**. The output of **doFinal()** varies with the symmetric block cipher mode in use. 3488 3489- In a single encryption process with GCM or CCM mode, concatenating the results of each **update()** and **doFinal()** procedures the ciphertext and **authTag**. In GCM mode, **authTag** is the last 16 bytes. In CCM mode, **authTag** is the last 12 bytes. The rest part is the ciphertext. If **data** passed to **doFinal()** is **null**, the **doFinal()** result is only the **authTag**. During decryption, **authTag** must be set in [GcmParamsSpec](#gcmparamsspec) or [CcmParamsSpec](#ccmparamsspec), and the ciphertext must be set in **data**. 3490- For other symmetric encryption and decryption modes and GCM and CCM decryption modes, concatenating the results of **update()** and **doFinal()** throughout the process will yield the complete plaintext or ciphertext. 3491 3492 3493 (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. 3494 3495> **NOTE** 3496> 3497> 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. 3498> 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. 3499> 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.<br> 3500> For encryption in CFB, OFB, or CTR mode, if **doFinal()** passes in **null**, the returned result is **null**.<br> 3501> For decryption in GCM, CCM, CFB, OFB, or CTR mode, if **doFinal()** passes in **null**, the returned result is **null**. For decryption in other modes, if **update** is called to pass in all the plaintext, which is an integer multiple of the encryption block size, and **doFinal()** is called to pass in **null**, the returned result is **null**.<br> 3502> 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. 3503 3504**Atomic service API**: This API can be used in atomic services since API version 12. 3505 3506**System capability**: SystemCapability.Security.CryptoFramework.Cipher 3507 3508The system capability is **SystemCapability.Security.CryptoFramework** in API versions 9 to 11, and **SystemCapability.Security.CryptoFramework.Cipher** since API version 12. 3509 3510**Parameters** 3511 3512| Name | Type | Mandatory| Description | 3513| -------- | ------------------------------------- | ---- | ------------------------------------------------------------ | 3514| data | [DataBlob](#datablob) \| null<sup>10+</sup> | Yes | Data to encrypt or decrypt. In symmetric encryption and decryption, this parameter can be **null**, but **{data: Uint8Array (empty)}** cannot be passed in. Before API version 10, only **DataBlob** is supported. Since API version 10, **null** is also supported. | 3515| callback | AsyncCallback\<[DataBlob](#datablob)> | Yes | Callback used to return the result. If the encryption or decryption is successful, **err** is **undefined**, and **data** is the encryption or decryption result **DataBlob**. Otherwise, **err** is an error object.| 3516 3517**Error codes** 3518For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 3519 3520| ID| Error Message | 3521| -------- | ----------------------- | 3522| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 3523| 17620001 | memory operation failed. | 3524| 17620002 | failed to convert parameters between arkts and c. | 3525| 17630001 | crypto operation error. | 3526 3527**Encryption with AES GCM (example)** 3528 3529For 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). 3530 3531```ts 3532import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 3533import { buffer } from '@kit.ArkTS'; 3534 3535function generateRandom(len: number) { 3536 let rand = cryptoFramework.createRandom(); 3537 let generateRandSync = rand.generateRandomSync(len); 3538 return generateRandSync; 3539} 3540 3541function genGcmParamsSpec() { 3542 let ivBlob = generateRandom(12); 3543 let arr = [1, 2, 3, 4, 5, 6, 7, 8]; 3544 let dataAad = new Uint8Array(arr); 3545 let aadBlob: cryptoFramework.DataBlob = { data: dataAad }; 3546 arr = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; 3547 let dataTag = new Uint8Array(arr); 3548 let tagBlob: cryptoFramework.DataBlob = { 3549 data: dataTag 3550 }; 3551 let gcmParamsSpec: cryptoFramework.GcmParamsSpec = { 3552 iv: ivBlob, 3553 aad: aadBlob, 3554 authTag: tagBlob, 3555 algName: "GcmParamsSpec" 3556 }; 3557 return gcmParamsSpec; 3558} 3559 3560function cipherByCallback() { 3561 let gcmParams = genGcmParamsSpec(); 3562 let symKeyGenerator = cryptoFramework.createSymKeyGenerator('AES128'); 3563 let cipher = cryptoFramework.createCipher('AES128|GCM|PKCS7'); 3564 symKeyGenerator.generateSymKey((err, symKey) => { 3565 cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, symKey, gcmParams, (err) => { 3566 let message = "This is a test"; 3567 let plainText: cryptoFramework.DataBlob = { data: new Uint8Array(buffer.from(message, 'utf-8').buffer) }; 3568 cipher.update(plainText, (err, encryptUpdate) => { 3569 cipher.doFinal(null, (err, tag) => { 3570 gcmParams.authTag = tag; 3571 console.info('encryptUpdate plainText: ' + encryptUpdate.data); 3572 }); 3573 }); 3574 }); 3575 }); 3576} 3577``` 3578 3579### doFinal 3580 3581doFinal(data: DataBlob | null): Promise\<DataBlob> 3582 3583 (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. 3584 3585- 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>During decryption, **authTag** must be set in [GcmParamsSpec](#gcmparamsspec) or [CcmParamsSpec](#ccmparamsspec), and the ciphertext must be set in **data**. 3586- For other symmetric encryption and decryption modes and GCM and CCM decryption modes, concatenating the results of **update()** and **doFinal()** throughout the process will yield the complete plaintext or ciphertext. 3587 3588(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 is to be processed, call **doFinal()** multiple times and concatenate the results to obtain the complete plaintext or ciphertext. 3589 3590> **NOTE** 3591> 3592> 1. In symmetric encryption and decryption, calling **doFinal()** indicates the completion of an encryption and decryption process, meaning the [Cipher](#cipher) instance status is cleared. When a new encryption or decryption process is started, **init()** must be called again with a full set of parameters. 3593> 3594> Even if the same **Cipher** instance and symmetric key are used for encryption and decryption, the **params** parameter must be set in **init()** instead of being **null**. 3595> 2. If decryption fails, check whether the data matches the parameters in **ini()**, for example, check whether **authTag** obtained during encryption in GCM mode is filled in **GcmParamsSpec** during decryption. 3596> 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. 3597> 3598> For encryption in CFB, OFB, or CTR mode, if **doFinal()** passes in **null**, the returned result is **null**. 3599> 3600> For decryption in GCM, CCM, CFB, OFB, or CTR mode, if **doFinal()** passes in **null**, the returned result is **null**. For decryption in other modes, if **update** is called to pass in all the plaintext, which is an integer multiple of the encryption block size, and **doFinal()** is called to pass in **null**, the returned result is **null**. 3601> 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. 3602 3603**Atomic service API**: This API can be used in atomic services since API version 12. 3604 3605**System capability**: SystemCapability.Security.CryptoFramework.Cipher 3606 3607The system capability is **SystemCapability.Security.CryptoFramework** in API versions 9 to 11, and **SystemCapability.Security.CryptoFramework.Cipher** since API version 12. 3608 3609**Parameters** 3610 3611| Name| Type | Mandatory| Description | 3612| ---- | --------------------- | ---- | -------------------- | 3613| 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.| 3614 3615**Return value** 3616 3617| Type | Description | 3618| ------------------------------- | ------------------------------------------------ | 3619| Promise\<[DataBlob](#datablob)> | Promise used to return the **DataBlob**, which is the encryption or decryption result of the remaining data.| 3620 3621**Error codes** 3622For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 3623 3624| ID| Error Message | 3625| -------- | -------------------------------------------- | 3626| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 3627| 17620001 | memory operation failed. | 3628| 17620002 | failed to convert parameters between arkts and c. | 3629| 17630001 | crypto operation error. | 3630 3631**Encryption with AES GCM (example)** 3632 3633For 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). 3634 3635```ts 3636import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 3637import { buffer } from '@kit.ArkTS'; 3638 3639function generateRandom(len: number) { 3640 let rand = cryptoFramework.createRandom(); 3641 let generateRandSync = rand.generateRandomSync(len); 3642 return generateRandSync; 3643} 3644 3645function genGcmParamsSpec() { 3646 let ivBlob = generateRandom(12); 3647 let arr = [1, 2, 3, 4, 5, 6, 7, 8]; 3648 let dataAad = new Uint8Array(arr); 3649 let aadBlob: cryptoFramework.DataBlob = { data: dataAad }; 3650 arr = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; 3651 let dataTag = new Uint8Array(arr); 3652 let tagBlob: cryptoFramework.DataBlob = { 3653 data: dataTag 3654 }; 3655 let gcmParamsSpec: cryptoFramework.GcmParamsSpec = { 3656 iv: ivBlob, 3657 aad: aadBlob, 3658 authTag: tagBlob, 3659 algName: "GcmParamsSpec" 3660 }; 3661 return gcmParamsSpec; 3662} 3663 3664async function cipherByPromise() { 3665 let gcmParams = genGcmParamsSpec(); 3666 let symKeyGenerator = cryptoFramework.createSymKeyGenerator('AES128'); 3667 let cipher = cryptoFramework.createCipher('AES128|GCM|PKCS7'); 3668 let symKey = await symKeyGenerator.generateSymKey(); 3669 await cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, symKey, gcmParams); 3670 let message = "This is a test"; 3671 let plainText: cryptoFramework.DataBlob = { data: new Uint8Array(buffer.from(message, 'utf-8').buffer) }; 3672 let encryptUpdate = await cipher.update(plainText); 3673 gcmParams.authTag = await cipher.doFinal(null); 3674 console.info('encryptUpdate plainText: ' + encryptUpdate.data); 3675} 3676``` 3677 3678### doFinalSync<sup>12+</sup> 3679 3680doFinalSync(data: DataBlob | null): DataBlob 3681 3682(1) Processes the remaining data and the data passed in this time, and completes the encryption or decryption operation for symmetric encryption and decryption. This API returns the encrypted or decrypted data synchronously. 3683 3684If a small amount of data is to be processed, you can pass in all the data at a time in **doFinalSync()** without using **updateSync()**. If data has been passed in by using [updateSync](#updatesync12) in the current encryption and decryption process, you can pass in **null** to the **data** parameter of **doFinalSync()**. 3685 3686The output of **doFinalSync()** varies with the symmetric block cipher mode in use. 3687 3688- In a single encryption process with GCM or CCM mode, concatenating the results of each **updateSync()** and **doFinalSync()** procedures the ciphertext and **authTag**. In GCM mode, **authTag** is the last 16 bytes. In CCM mode, **authTag** is the last 12 bytes. The rest part is the ciphertext. If **data** in **doFinalSync()** is **null**, the result of **doFinalSync()** is **authTag**. 3689 3690 During decryption, **authTag** must be set in [GcmParamsSpec](#gcmparamsspec) or [CcmParamsSpec](#ccmparamsspec), and the ciphertext must be set in **data**. 3691- For other symmetric encryption and decryption modes and GCM and CCM decryption modes, concatenating the results of **updateSync()** and **doFinalSync()** throughout the process will yield the complete plaintext or ciphertext. 3692 3693(2) Encrypts or decrypts the input data for RSA or SM2 asymmetric encryption/decryption. This API returns the encrypted or decrypted data synchronously. If a large amount of data is to be processed, call **doFinalSync()** multiple times and concatenate the results to obtain the complete plaintext or ciphertext. 3694 3695See **NOTE** in [doFinal()](#dofinal) for other precautions. 3696 3697**Atomic service API**: This API can be used in atomic services since API version 12. 3698 3699**System capability**: SystemCapability.Security.CryptoFramework.Cipher 3700 3701**Parameters** 3702 3703| Name| Type | Mandatory| Description | 3704| ------ | ------------------------------------------- | ---- | ------------------------------------------------------------ | 3705| data | [DataBlob](#datablob) \| null| Yes | Data to encrypt or decrypt. It can be **null** in symmetric encryption or decryption, but cannot be {data:Uint8Array(empty)}.| 3706 3707**Return value** 3708 3709| Type | Description | 3710| ------------------------------- | ------------------------------------------------ | 3711| [DataBlob](#datablob) | Encrypted or decrypted data.| 3712 3713**Error codes** 3714For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 3715 3716| ID| Error Message | 3717| -------- | ----------------------- | 3718| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 3719| 17620001 | memory operation failed. | 3720| 17620002 | failed to convert parameters between arkts and c. | 3721| 17630001 | crypto operation error. | 3722 3723**Encryption with AES GCM (example)** 3724 3725For 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). 3726 3727```ts 3728import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 3729import { buffer } from '@kit.ArkTS'; 3730 3731function generateRandom(len: number) { 3732 let rand = cryptoFramework.createRandom(); 3733 let generateRandSync = rand.generateRandomSync(len); 3734 return generateRandSync; 3735} 3736 3737function genGcmParamsSpec() { 3738 let ivBlob = generateRandom(12); 3739 let arr = [1, 2, 3, 4, 5, 6, 7, 8]; 3740 let dataAad = new Uint8Array(arr); 3741 let aadBlob: cryptoFramework.DataBlob = { data: dataAad }; 3742 arr = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; 3743 let dataTag = new Uint8Array(arr); 3744 let tagBlob: cryptoFramework.DataBlob = { 3745 data: dataTag 3746 }; 3747 let gcmParamsSpec: cryptoFramework.GcmParamsSpec = { 3748 iv: ivBlob, 3749 aad: aadBlob, 3750 authTag: tagBlob, 3751 algName: "GcmParamsSpec" 3752 }; 3753 return gcmParamsSpec; 3754} 3755 3756async function cipherBySync() { 3757 let gcmParams = genGcmParamsSpec(); 3758 let symKeyGenerator = cryptoFramework.createSymKeyGenerator('AES128'); 3759 let cipher = cryptoFramework.createCipher('AES128|GCM|PKCS7'); 3760 let symKey = await symKeyGenerator.generateSymKey(); 3761 await cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, symKey, gcmParams); 3762 let message = "This is a test"; 3763 let plainText: cryptoFramework.DataBlob = { data: new Uint8Array(buffer.from(message, 'utf-8').buffer) }; 3764 let encryptUpdate = cipher.updateSync(plainText); 3765 gcmParams.authTag = cipher.doFinalSync(null); 3766 console.info('encryptUpdate plainText: ' + encryptUpdate.data); 3767} 3768 3769``` 3770 3771### setCipherSpec<sup>10+</sup> 3772 3773setCipherSpec(itemType: CipherSpecItem, itemValue: Uint8Array): void 3774 3775Sets cipher specifications. You can use this API to set cipher specifications that cannot be set by [createCipher](#cryptoframeworkcreatecipher). Currently, only RSA is supported. 3776 3777**Atomic service API**: This API can be used in atomic services since API version 12. 3778 3779**System capability**: SystemCapability.Security.CryptoFramework.Cipher 3780 3781The system capability is **SystemCapability.Security.CryptoFramework** in API versions 10 to 11, and **SystemCapability.Security.CryptoFramework.Cipher** since API version 12. 3782 3783**Parameters** 3784 3785| Name | Type | Mandatory| Description | 3786| -------- | -------------------- | ---- | ---------- | 3787| itemType | [CipherSpecItem](#cipherspecitem10) | Yes | Cipher parameter to set.| 3788| itemValue | Uint8Array | Yes | Value of the parameter to set.| 3789 3790**Error codes** 3791For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 3792 3793| ID| Error Message | 3794| -------- | ---------------------- | 3795| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 3796| 801 | this operation is not supported. | 3797| 17620001 | memory operation failed. | 3798| 17630001 | crypto operation error. | 3799 3800**Example** 3801 3802<!--code_no_check--> 3803```ts 3804let cipher: cryptoFramework.Cipher; // The process of generating the Cipher instance is omitted here. 3805let pSource = new Uint8Array([1,2,3,4]); 3806cipher.setCipherSpec(cryptoFramework.CipherSpecItem.OAEP_MGF1_PSRC_UINT8ARR, pSource); 3807``` 3808 3809### getCipherSpec<sup>10+</sup> 3810 3811getCipherSpec(itemType: CipherSpecItem): string | Uint8Array 3812 3813Obtains cipher specifications. Currently, only RSA and SM2 (available since API version 11) are supported. 3814 3815**Atomic service API**: This API can be used in atomic services since API version 12. 3816 3817**System capability**: SystemCapability.Security.CryptoFramework.Cipher 3818 3819The system capability is **SystemCapability.Security.CryptoFramework** in API versions 10 to 11, and **SystemCapability.Security.CryptoFramework.Cipher** since API version 12. 3820 3821**Parameters** 3822 3823| Name| Type | Mandatory| Description | 3824| ------ | -------- | ---- | ---------- | 3825| itemType | [CipherSpecItem](#cipherspecitem10) | Yes | Cipher parameter to obtain.| 3826 3827**Return value** 3828 3829| Type | Description | 3830| -------------- | ----------- | 3831| string \| Uint8Array | Returns the value of the cipher parameter obtained.| 3832 3833**Error codes** 3834For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 3835 3836| ID| Error Message | 3837| -------- | ---------------------- | 3838| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 3839| 801 | this operation is not supported. | 3840| 17620001 | memory operation failed. | 3841| 17630001 | crypto operation error. | 3842 3843**Example** 3844 3845<!--code_no_check--> 3846```ts 3847let cipher: cryptoFramework.Cipher; // The process of generating the Cipher instance is omitted here. 3848let mdName = cipher.getCipherSpec(cryptoFramework.CipherSpecItem.OAEP_MD_NAME_STR); 3849``` 3850 3851## cryptoFramework.createSign 3852 3853createSign(algName: string): Sign 3854 3855Creates a **Sign** instance. 3856 3857For details about the supported specifications, see [Signing and Signature Verification Overview and Algorithm Specifications](../../security/CryptoArchitectureKit/crypto-sign-sig-verify-overview.md). 3858 3859**Atomic service API**: This API can be used in atomic services since API version 12. 3860 3861**System capability**: SystemCapability.Security.CryptoFramework.Signature 3862 3863The system capability is **SystemCapability.Security.CryptoFramework** in API versions 9 to 11, and **SystemCapability.Security.CryptoFramework.Signature** since API version 12. 3864 3865**Parameters** 3866 3867| Name | Type | Mandatory| Description | 3868| ------- | ------ | ---- | ------------------------------------------------------------ | 3869| algName | string | Yes | Signing algorithm to use. Currently, RSA, ECC, DSA, SM2<sup>10+</sup> and Ed25519<sup>11+</sup> are supported. If RSA PKCS1 is used, you must set the digest. If RSA PSS is used, you must set the digest and mask digest. For signing, you can set **OnlySign** to enable the data digest to be used for signing only.| 3870 3871**Return value** 3872 3873| Type| Description | 3874| ---- | ---------------------------------- | 3875| [Sign](#sign) | Returns the **Sign** instance created.| 3876 3877**Error codes** 3878For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 3879 3880| ID| Error Message | 3881| -------- | ---------------------- | 3882| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 3883| 801 | this operation is not supported. | 3884| 17620001 | memory operation failed. | 3885 3886**Example** 3887 3888```ts 3889import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 3890 3891let signer1 = cryptoFramework.createSign('RSA1024|PKCS1|SHA256'); 3892 3893let signer2 = cryptoFramework.createSign('RSA1024|PSS|SHA256|MGF1_SHA256'); 3894 3895let signer3 = cryptoFramework.createSign('ECC224|SHA256'); 3896 3897let signer4 = cryptoFramework.createSign('DSA2048|SHA256'); 3898 3899let signer5 = cryptoFramework.createSign('RSA1024|PKCS1|SHA256|OnlySign'); 3900``` 3901 3902## Sign 3903 3904Provides 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). 3905 3906The **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. 3907 3908The signing mode is determined by **createSign()**, and the key is set by **init()**. 3909 3910If a small amount of data is to be signed, you can directly call **sign()** to pass in the data for signing after **ini()**. 3911 3912If a large amount of data is to be signed, you can use **update()** to pass in the data by segment, and then use **sign()** to sign the entire data. 3913 3914When **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()**, call **sign()** to sign the data. 3915 3916If the DSA algorithm is used for signing and the digest algorithm is **NoHash**, the **update()** operation is not supported. If **update()** is called in this case, the error code **ERR_CRYPTO_OPERATION** will be returned. 3917 3918### Attributes 3919 3920**Atomic service API**: This API can be used in atomic services since API version 12. 3921 3922**System capability**: SystemCapability.Security.CryptoFramework.Signature 3923 3924The system capability is **SystemCapability.Security.CryptoFramework** in API versions 9 to 11, and **SystemCapability.Security.CryptoFramework.Signature** since API version 12. 3925 3926| Name | Type | Read-Only| Optional| Description | 3927| ------- | ------ | ---- | ---- | ---------------------------- | 3928| algName | string | Yes | No | Algorithm to use.| 3929 3930### init 3931 3932init(priKey: PriKey, callback: AsyncCallback\<void>): void 3933 3934Initializes 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. 3935 3936The **Sign** class does not support repeated use of **ini**. 3937 3938**Atomic service API**: This API can be used in atomic services since API version 12. 3939 3940**System capability**: SystemCapability.Security.CryptoFramework.Signature 3941 3942The system capability is **SystemCapability.Security.CryptoFramework** in API versions 9 to 11, and **SystemCapability.Security.CryptoFramework.Signature** since API version 12. 3943 3944**Parameters** 3945 3946| Name | Type | Mandatory| Description | 3947| -------- | -------------------- | ---- | ---------------- | 3948| priKey | [PriKey](#prikey) | Yes | Private key used for the initialization.| 3949| callback | AsyncCallback\<void> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.| 3950 3951**Error codes** 3952For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 3953 3954| ID| Error Message | 3955| -------- | ---------------------- | 3956| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 3957| 17620001 | memory operation failed. | 3958| 17620002 | failed to convert parameters between arkts and c. | 3959| 17630001 | crypto operation error. | 3960 3961### init 3962 3963init(priKey: PriKey): Promise\<void> 3964 3965Initializes 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. 3966 3967The **Sign** class does not support repeated use of **ini**. 3968 3969**Atomic service API**: This API can be used in atomic services since API version 12. 3970 3971**System capability**: SystemCapability.Security.CryptoFramework.Signature 3972 3973The system capability is **SystemCapability.Security.CryptoFramework** in API versions 9 to 11, and **SystemCapability.Security.CryptoFramework.Signature** since API version 12. 3974 3975**Parameters** 3976 3977| Name| Type| Mandatory| Description | 3978| ------ | ---- | ---- | ---------------- | 3979| priKey | [PriKey](#prikey) | Yes | Private key used for the initialization.| 3980 3981**Return value** 3982 3983| Type | Description | 3984| -------------- | ------------- | 3985| Promise\<void> | Promise that returns no value.| 3986 3987**Error codes** 3988For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 3989 3990| ID| Error Message | 3991| -------- | ---------------------- | 3992| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 3993| 17620001 | memory operation failed. | 3994| 17620002 | failed to convert parameters between arkts and c. | 3995| 17630001 | crypto operation error. | 3996 3997### initSync<sup>12+</sup> 3998 3999initSync(priKey: PriKey): void 4000 4001Initializes 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. 4002 4003The **Sign** class does not support repeated use of **initSync**. 4004 4005**Atomic service API**: This API can be used in atomic services since API version 12. 4006 4007**System capability**: SystemCapability.Security.CryptoFramework.Signature 4008 4009**Parameters** 4010 4011| Name| Type| Mandatory| Description | 4012| ------ | ---- | ---- | ---------------- | 4013| priKey | [PriKey](#prikey) | Yes | Private key used for the initialization.| 4014 4015**Error codes** 4016For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 4017 4018| ID| Error Message | 4019| -------- | ---------------------- | 4020| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 4021| 17620001 | memory operation failed. | 4022| 17620002 | failed to convert parameters between arkts and c. | 4023| 17630001 | crypto operation error. | 4024 4025### update 4026 4027update(data: DataBlob, callback: AsyncCallback\<void>): void 4028 4029Updates the data to be signed. This API uses an asynchronous callback to return the result. 4030 4031This API can be called only after the [Sign](#sign) instance is initialized by using [init()](#init-2). 4032 4033> **NOTE** 4034> 4035> 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> 4036> 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> 4037> 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> 4038> **OnlySign** cannot be used with **update()**. If **OnlySign** is specified, use **sign()** to pass in data.<br> 4039> 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. 4040 4041**Atomic service API**: This API can be used in atomic services since API version 12. 4042 4043**System capability**: SystemCapability.Security.CryptoFramework.Signature 4044 4045The system capability is **SystemCapability.Security.CryptoFramework** in API versions 9 to 11, and **SystemCapability.Security.CryptoFramework.Signature** since API version 12. 4046 4047**Parameters** 4048 4049| Name | Type | Mandatory| Description | 4050| -------- | --------------------- | ---- | ------------ | 4051| data | [DataBlob](#datablob) | Yes | Data to pass in.| 4052| callback | AsyncCallback\<void> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.| 4053 4054**Error codes** 4055For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 4056 4057| ID| Error Message | 4058| -------- | ---------------------- | 4059| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 4060| 17620001 | memory operation failed. | 4061| 17620002 | failed to convert parameters between arkts and c. | 4062| 17630001 | crypto operation error. | 4063 4064### update 4065 4066update(data: DataBlob): Promise\<void> 4067 4068Updates the data to be signed. This API uses a promise to return the result. 4069 4070Before using this API, you must use [Sign](#sign) to initialize the [init()](#init-3) instance. 4071 4072> **NOTE** 4073> 4074> 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> 4075> 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. 4076> 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> 4077> **OnlySign** cannot be used with **update()**. If **OnlySign** is specified, use **sign()** to pass in data.<br> 4078> 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. 4079 4080**Atomic service API**: This API can be used in atomic services since API version 12. 4081 4082**System capability**: SystemCapability.Security.CryptoFramework.Signature 4083 4084The system capability is **SystemCapability.Security.CryptoFramework** in API versions 9 to 11, and **SystemCapability.Security.CryptoFramework.Signature** since API version 12. 4085 4086**Parameters** 4087 4088| Name| Type | Mandatory| Description | 4089| ------ | -------- | ---- | ---------- | 4090| data | [DataBlob](#datablob) | Yes | Data to pass in.| 4091 4092**Return value** 4093 4094| Type | Description | 4095| -------------- | ------------- | 4096| Promise\<void> | Promise that returns no value.| 4097 4098**Error codes** 4099For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 4100 4101| ID| Error Message | 4102| -------- | ---------------------- | 4103| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 4104| 17620001 | memory operation failed. | 4105| 17620002 | failed to convert parameters between arkts and c. | 4106| 17630001 | crypto operation error. | 4107 4108### updateSync<sup>12+</sup> 4109 4110updateSync(data: DataBlob): void 4111 4112Updates the data to be signed. This API returns the result synchronously. 4113 4114This API can be called only after the [Sign](#sign) instance is initialized by using [initSync()](#initsync12-1). 4115 4116> **NOTE** 4117> 4118> You can call **updateSync** multiple times or do not use **updateSync** (call [signSync](#signsync12) after [initSync](#initsync12-1)), depending on the data volume.<br> 4119> 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> 4120> 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> 4121> **OnlySign** cannot be used with **updateSync**. If **OnlySign** is specified, use **signSync** to pass in data.<br> 4122> 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. 4123 4124**Atomic service API**: This API can be used in atomic services since API version 12. 4125 4126**System capability**: SystemCapability.Security.CryptoFramework.Signature 4127 4128**Parameters** 4129 4130| Name| Type | Mandatory| Description | 4131| ------ | -------- | ---- | ---------- | 4132| data | [DataBlob](#datablob) | Yes | Data to pass in.| 4133 4134**Return value** 4135 4136| Type | Description | 4137| -------------- | ------------- | 4138| void | No value is returned.| 4139 4140**Error codes** 4141For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 4142 4143| ID| Error Message | 4144| -------- | ---------------------- | 4145| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 4146| 17620001 | memory operation failed. | 4147| 17620002 | failed to convert parameters between arkts and c. | 4148| 17630001 | crypto operation error. | 4149 4150### sign 4151 4152sign(data: DataBlob | null, callback: AsyncCallback\<DataBlob>): void 4153 4154Signs the data. This API uses an asynchronous callback to return the result. 4155 4156**Atomic service API**: This API can be used in atomic services since API version 12. 4157 4158**System capability**: SystemCapability.Security.CryptoFramework.Signature 4159 4160The system capability is **SystemCapability.Security.CryptoFramework** in API versions 9 to 11, and **SystemCapability.Security.CryptoFramework.Signature** since API version 12. 4161 4162**Parameters** 4163 4164| Name | Type | Mandatory| Description | 4165| -------- | -------------------- | ---- | ---------- | 4166| 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.| 4167| callback | AsyncCallback\<[DataBlob](#datablob)> | Yes | Callback used to return a **DataBlob** object.| 4168 4169**Error codes** 4170For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 4171 4172| ID| Error Message | 4173| -------- | ---------------------- | 4174| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 4175| 17620001 | memory operation failed. | 4176| 17620002 | failed to convert parameters between arkts and c. | 4177| 17630001 | crypto operation error. | 4178 4179### sign 4180 4181sign(data: DataBlob | null): Promise\<DataBlob> 4182 4183Signs the data. This API uses a promise to return the result. 4184 4185**Atomic service API**: This API can be used in atomic services since API version 12. 4186 4187**System capability**: SystemCapability.Security.CryptoFramework.Signature 4188 4189The system capability is **SystemCapability.Security.CryptoFramework** in API versions 9 to 11, and **SystemCapability.Security.CryptoFramework.Signature** since API version 12. 4190 4191**Parameters** 4192 4193| Name| Type | Mandatory| Description | 4194| ------ | -------- | ---- | ---------- | 4195| data | [DataBlob](#datablob) \| null<sup>10+</sup> | Yes | Data to pass in.| 4196 4197**Return value** 4198 4199| Type | Description | 4200| -------------- | ------------- | 4201| Promise\<[DataBlob](#datablob)> | Signature.| 4202 4203**Error codes** 4204For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 4205 4206| ID| Error Message | 4207| -------- | ---------------------- | 4208| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 4209| 17620001 | memory operation failed. | 4210| 17620002 | failed to convert parameters between arkts and c. | 4211| 17630001 | crypto operation error. | 4212 4213### signSync<sup>12+</sup> 4214 4215signSync(data: DataBlob | null): DataBlob 4216 4217Signs the data. This API returns the result synchronously. 4218 4219**Atomic service API**: This API can be used in atomic services since API version 12. 4220 4221**System capability**: SystemCapability.Security.CryptoFramework.Signature 4222 4223**Parameters** 4224 4225| Name| Type | Mandatory| Description | 4226| ------ | -------- | ---- | ---------- | 4227| data | [DataBlob](#datablob) \| null | Yes | Data to pass in.| 4228 4229**Return value** 4230 4231| Type | Description | 4232| -------------- | ------------- | 4233| [DataBlob](#datablob) | Signature.| 4234 4235**Error codes** 4236For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 4237 4238| ID| Error Message | 4239| -------- | ---------------------- | 4240| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 4241| 17620001 | memory operation failed. | 4242| 17620002 | failed to convert parameters between arkts and c. | 4243| 17630001 | crypto operation error. | 4244 4245**Example (using the callback-based API)** 4246 4247For 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). 4248 4249```ts 4250import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 4251import { buffer } from '@kit.ArkTS'; 4252 4253function signByCallback() { 4254 let inputUpdate: cryptoFramework.DataBlob = { data: new Uint8Array(buffer.from("This is Sign test plan1", 'utf-8').buffer) }; 4255 let inputVerify: cryptoFramework.DataBlob = { data: new Uint8Array(buffer.from("This is Sign test plan2", 'utf-8').buffer) }; 4256 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]); 4257 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]); 4258 let pubKeyBlob: cryptoFramework.DataBlob = { data: pkData }; 4259 let priKeyBlob: cryptoFramework.DataBlob = { data: skData }; 4260 let rsaGenerator = cryptoFramework.createAsyKeyGenerator('RSA1024'); 4261 let signer = cryptoFramework.createSign('RSA1024|PKCS1|SHA256'); 4262 rsaGenerator.convertKey(pubKeyBlob, priKeyBlob, (err, keyPair) => { 4263 signer.init(keyPair.priKey, err => { 4264 signer.update(inputUpdate, err => { 4265 signer.sign(inputVerify, (err, signData) => { 4266 console.info('sign output is ' + signData.data); 4267 }); 4268 }); 4269 }); 4270 }); 4271} 4272``` 4273 4274**Example (using the promise-based API)** 4275 4276For 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). 4277 4278```ts 4279import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 4280import { buffer } from '@kit.ArkTS'; 4281 4282async function genKeyPairByData(pubKeyData: Uint8Array, priKeyData: Uint8Array) { 4283 let pubKeyBlob: cryptoFramework.DataBlob = { data: pubKeyData }; 4284 let priKeyBlob: cryptoFramework.DataBlob = { data: priKeyData }; 4285 let rsaGenerator = cryptoFramework.createAsyKeyGenerator('RSA1024'); 4286 let keyPair = await rsaGenerator.convertKey(pubKeyBlob, priKeyBlob); 4287 console.info('convertKey success'); 4288 return keyPair; 4289} 4290 4291async function signByPromise() { 4292 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]); 4293 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]); 4294 let keyPair = await genKeyPairByData(pkData, skData); 4295 let inputUpdate: cryptoFramework.DataBlob = { data: new Uint8Array(buffer.from("This is Sign test plan1", 'utf-8').buffer) }; 4296 let inputSign: cryptoFramework.DataBlob = { data: new Uint8Array(buffer.from("This is Sign test plan2", 'utf-8').buffer) }; 4297 let signer = cryptoFramework.createSign('RSA1024|PKCS1|SHA256'); 4298 await signer.init(keyPair.priKey); 4299 await signer.update(inputUpdate); 4300 let signData = await signer.sign(inputSign); 4301 console.info('signData result: ' + signData.data); 4302} 4303``` 4304 4305**Example (using the sync API)** 4306 4307For 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). 4308 4309```ts 4310import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 4311import { buffer } from '@kit.ArkTS'; 4312 4313function genKeyPairByData(pubKeyData: Uint8Array, priKeyData: Uint8Array) { 4314 let pubKeyBlob: cryptoFramework.DataBlob = { data: pubKeyData }; 4315 let priKeyBlob: cryptoFramework.DataBlob = { data: priKeyData }; 4316 let rsaGenerator = cryptoFramework.createAsyKeyGenerator('RSA1024'); 4317 let keyPair = rsaGenerator.convertKeySync(pubKeyBlob, priKeyBlob); 4318 console.info('convertKeySync success'); 4319 return keyPair; 4320} 4321 4322function signBySync() { 4323 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]); 4324 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]); 4325 let keyPair = genKeyPairByData(pkData, skData); 4326 let inputUpdate: cryptoFramework.DataBlob = { data: new Uint8Array(buffer.from("This is Sign test plan1", 'utf-8').buffer) }; 4327 let inputSign: cryptoFramework.DataBlob = { data: new Uint8Array(buffer.from("This is Sign test plan2", 'utf-8').buffer) }; 4328 let signer = cryptoFramework.createSign('RSA1024|PKCS1|SHA256'); 4329 signer.initSync(keyPair.priKey); 4330 signer.updateSync(inputUpdate); 4331 let signData = signer.signSync(inputSign); 4332 console.info('signData result: ' + signData.data); 4333} 4334``` 4335 4336### setSignSpec<sup>10+</sup> 4337 4338setSignSpec(itemType: SignSpecItem, itemValue: number): void 4339 4340setSignSpec(itemType: SignSpecItem, itemValue: number \| Uint8Array): void 4341 4342Sets signing specifications. You can use this API to set signing parameters that cannot be set by **createSign**. 4343 4344 4345Currently, only RSA and SM2 are supported. Since API version 11, SM2 signing parameters can be set. 4346 4347**Atomic service API**: This API can be used in atomic services since API version 12. 4348 4349**System capability**: SystemCapability.Security.CryptoFramework.Signature 4350 4351The system capability is **SystemCapability.Security.CryptoFramework** in API versions 10 to 11, and **SystemCapability.Security.CryptoFramework.Signature** since API version 12. 4352 4353**Parameters** 4354 4355| Name | Type | Mandatory| Description | 4356| -------- | -------------------- | ---- | ---------- | 4357| itemType | [SignSpecItem](#signspecitem10) | Yes | Signing parameter to set.| 4358| itemValue | number \| Uint8Array<sup>11+</sup> | Yes | Value of the signing parameter to set.| 4359 4360**Error codes** 4361For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 4362 4363| ID| Error Message | 4364| -------- | ---------------------- | 4365| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 4366| 801 | this operation is not supported. | 4367| 17620001 | memory operation failed. | 4368| 17630001 | crypto operation error. | 4369 4370**Example** 4371 4372<!--code_no_check--> 4373```ts 4374let signer: cryptoFramework.Sign; // The process of generating the Sign instance is omitted here. 4375let setN = 20; 4376signer.setSignSpec(cryptoFramework.SignSpecItem.PSS_SALT_LEN_NUM, setN); 4377``` 4378 4379### getSignSpec<sup>10+</sup> 4380 4381getSignSpec(itemType: SignSpecItem): string | number 4382 4383Obtains signing specifications. Currently, only RSA is supported. 4384 4385**Atomic service API**: This API can be used in atomic services since API version 12. 4386 4387**System capability**: SystemCapability.Security.CryptoFramework.Signature 4388 4389The system capability is **SystemCapability.Security.CryptoFramework** in API versions 10 to 11, and **SystemCapability.Security.CryptoFramework.Signature** since API version 12. 4390 4391**Parameters** 4392 4393| Name| Type | Mandatory| Description | 4394| ------ | -------- | ---- | ---------- | 4395| itemType | [SignSpecItem](#signspecitem10) | Yes | Signing parameter to obtain.| 4396 4397**Return value** 4398 4399| Type | Description | 4400| -------------- | ----------- | 4401| string \| number | Returns the value of the signing parameter obtained.| 4402 4403**Error codes** 4404For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 4405 4406| ID| Error Message | 4407| -------- | ---------------------- | 4408| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 4409| 801 | this operation is not supported. | 4410| 17620001 | memory operation failed. | 4411| 17630001 | crypto operation error. | 4412 4413**Example** 4414 4415<!--code_no_check--> 4416```ts 4417let signer: cryptoFramework.Sign; // The process of generating the Sign instance is omitted here. 4418let saltLen = signer.getSignSpec(cryptoFramework.SignSpecItem.PSS_SALT_LEN_NUM); 4419``` 4420 4421## cryptoFramework.createVerify 4422 4423createVerify(algName: string): Verify 4424 4425Creates a **Verify** instance. 4426 4427For details about the supported specifications, see [Signing and Signature Verification Overview and Algorithm Specifications](../../security/CryptoArchitectureKit/crypto-sign-sig-verify-overview.md). 4428 4429**Atomic service API**: This API can be used in atomic services since API version 12. 4430 4431**System capability**: SystemCapability.Security.CryptoFramework.Signature 4432 4433The system capability is **SystemCapability.Security.CryptoFramework** in API versions 9 to 11, and **SystemCapability.Security.CryptoFramework.Signature** since API version 12. 4434 4435**Parameters** 4436 4437| Name | Type | Mandatory| Description | 4438| ------- | ------ | ---- | ------------------------------------------------------------ | 4439| algName | string | Yes | Signing algorithm to use. Currently, RSA, ECC, DSA, SM2<sup>10+</sup> and Ed25519<sup>11+</sup> are supported. If RSA PKCS1 is used, you must set the digest. If RSA PSS is used, you must set the digest and mask digest. When the RSA algorithm is used for signature verification, you can use **Recover** to verify and recover the signed data.| 4440 4441**Return value** 4442 4443| Type | Description | 4444| ------ | ------------------------------------ | 4445| Verify | Returns the **Verify** instance created.| 4446 4447**Error codes** 4448For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 4449 4450| ID| Error Message | 4451| -------- | ---------------------- | 4452| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 4453| 801 | this operation is not supported. | 4454| 17620001 | memory operation failed. | 4455 4456**Example** 4457 4458```ts 4459import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 4460 4461let verifyer1 = cryptoFramework.createVerify('RSA1024|PKCS1|SHA256'); 4462 4463let verifyer2 = cryptoFramework.createVerify('RSA1024|PSS|SHA256|MGF1_SHA256'); 4464 4465let verifyer3 = cryptoFramework.createVerify('RSA1024|PKCS1|SHA256|Recover'); 4466``` 4467 4468## Verify 4469 4470Provides 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). 4471 4472The **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. 4473 4474The signature verification mode is determined in **createVerify()**, and the key is set by **init()**. 4475 4476If 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()**. 4477 4478If 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. 4479 4480If 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. 4481 4482### Attributes 4483 4484**Atomic service API**: This API can be used in atomic services since API version 12. 4485 4486**System capability**: SystemCapability.Security.CryptoFramework.Signature 4487 4488The system capability is **SystemCapability.Security.CryptoFramework** in API versions 9 to 11, and **SystemCapability.Security.CryptoFramework.Signature** since API version 12. 4489 4490| Name | Type | Read-Only| Optional| Description | 4491| ------- | ------ | ---- | ---- | ---------------------------- | 4492| algName | string | Yes | No | Algorithm to be used for signature verification.| 4493 4494### init 4495 4496init(pubKey: PubKey, callback: AsyncCallback\<void>): void 4497 4498Initializes 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. 4499 4500**Atomic service API**: This API can be used in atomic services since API version 12. 4501 4502**System capability**: SystemCapability.Security.CryptoFramework.Signature 4503 4504The system capability is **SystemCapability.Security.CryptoFramework** in API versions 9 to 11, and **SystemCapability.Security.CryptoFramework.Signature** since API version 12. 4505 4506**Parameters** 4507 4508| Name | Type | Mandatory| Description | 4509| -------- | -------------------- | ---- | ------------------------------ | 4510| pubKey | [PubKey](#pubkey) | Yes | Public key used to initialize the **Verify** instance.| 4511| callback | AsyncCallback\<void> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object. | 4512 4513**Error codes** 4514For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 4515 4516| ID| Error Message | 4517| -------- | ---------------------- | 4518| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 4519| 17620001 | memory operation failed. | 4520| 17620002 | failed to convert parameters between arkts and c. | 4521| 17630001 | crypto operation error. | 4522 4523### init 4524 4525init(pubKey: PubKey): Promise\<void> 4526 4527Initializes 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. 4528 4529**Atomic service API**: This API can be used in atomic services since API version 12. 4530 4531**System capability**: SystemCapability.Security.CryptoFramework.Signature 4532 4533The system capability is **SystemCapability.Security.CryptoFramework** in API versions 9 to 11, and **SystemCapability.Security.CryptoFramework.Signature** since API version 12. 4534 4535**Parameters** 4536 4537| Name| Type| Mandatory| Description | 4538| ------ | ---- | ---- | ---------------------------- | 4539| pubKey | [PubKey](#pubkey) | Yes | Public key used to initialize the **Verify** instance.| 4540 4541**Return value** 4542 4543| Type | Description | 4544| -------------- | ------------- | 4545| Promise\<void> | Promise that returns no value.| 4546 4547**Error codes** 4548For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 4549 4550| ID| Error Message | 4551| -------- | ---------------------- | 4552| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 4553| 17620001 | memory operation failed. | 4554| 17620002 | failed to convert parameters between arkts and c. | 4555| 17630001 | crypto operation error. | 4556 4557### initSync<sup>12+</sup> 4558 4559initSync(pubKey: PubKey): void 4560 4561Initializes 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. 4562 4563**Atomic service API**: This API can be used in atomic services since API version 12. 4564 4565**System capability**: SystemCapability.Security.CryptoFramework.Signature 4566 4567**Parameters** 4568 4569| Name| Type| Mandatory| Description | 4570| ------ | ---- | ---- | ---------------------------- | 4571| pubKey | [PubKey](#pubkey) | Yes | Public key used to initialize the **Verify** instance.| 4572 4573**Return value** 4574 4575| Type | Description | 4576| -------------- | ------------- | 4577| void | No value is returned.| 4578 4579**Error codes** 4580For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 4581 4582| ID| Error Message | 4583| -------- | ---------------------- | 4584| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 4585| 17620001 | memory operation failed. | 4586| 17620002 | failed to convert parameters between arkts and c. | 4587| 17630001 | crypto operation error. | 4588 4589### update 4590 4591update(data: DataBlob, callback: AsyncCallback\<void>): void 4592 4593Updates the data for signature verification. This API uses an asynchronous callback to return the result. 4594 4595This API can be called only after the [Verify](#verify) instance is initialized using [init](#init-4). 4596 4597> **NOTE** 4598> 4599> 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> 4600> 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> 4601> 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> 4602> 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. 4603 4604**Atomic service API**: This API can be used in atomic services since API version 12. 4605 4606**System capability**: SystemCapability.Security.CryptoFramework.Signature 4607 4608The system capability is **SystemCapability.Security.CryptoFramework** in API versions 9 to 11, and **SystemCapability.Security.CryptoFramework.Signature** since API version 12. 4609 4610**Parameters** 4611 4612| Name | Type | Mandatory| Description | 4613| -------- | --------------------- | ---- | ------------ | 4614| data | [DataBlob](#datablob) | Yes | Data to pass in.| 4615| callback | AsyncCallback\<void> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.| 4616 4617**Error codes** 4618For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 4619 4620| ID| Error Message | 4621| -------- | ---------------------- | 4622| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 4623| 17620001 | memory operation failed. | 4624| 17620002 | failed to convert parameters between arkts and c. | 4625| 17630001 | crypto operation error. | 4626 4627### update 4628 4629update(data: DataBlob): Promise\<void> 4630 4631Updates the data for signature verifications. This API uses a promise to return the result. 4632 4633This API can be called only after the [Verify](#verify) instance is initialized using [init()](#init-5). 4634 4635> **NOTE** 4636> 4637> 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> 4638> 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> 4639> 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> 4640> 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. 4641 4642**Atomic service API**: This API can be used in atomic services since API version 12. 4643 4644**System capability**: SystemCapability.Security.CryptoFramework.Signature 4645 4646The system capability is **SystemCapability.Security.CryptoFramework** in API versions 9 to 11, and **SystemCapability.Security.CryptoFramework.Signature** since API version 12. 4647 4648**Parameters** 4649 4650| Name| Type | Mandatory| Description | 4651| ------ | -------- | ---- | ---------- | 4652| data | [DataBlob](#datablob) | Yes | Data to pass in.| 4653 4654**Return value** 4655 4656| Type | Description | 4657| -------------- | ------------- | 4658| Promise\<void> | Promise that returns no value.| 4659 4660**Error codes** 4661For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 4662 4663| ID| Error Message | 4664| -------- | ---------------------- | 4665| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 4666| 17620001 | memory operation failed. | 4667| 17620002 | failed to convert parameters between arkts and c. | 4668| 17630001 | crypto operation error. | 4669 4670### updateSync<sup>12+</sup> 4671 4672updateSync(data: DataBlob): void 4673 4674Updates the data for signature verifications. This API returns the result synchronously. 4675 4676This API can be called only after the [Verify](#verify) instance is initialized by using [initSync()](#initsync12-2). 4677 4678> **NOTE** 4679> 4680> You can call **updateSync** multiple times or do not use **updateSync** (call [verifySync](#verifysync12)after [initSync](#initsync12-2)), depending on the data volume.<br> 4681> 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> 4682> 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> 4683> 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. 4684 4685**Atomic service API**: This API can be used in atomic services since API version 12. 4686 4687**System capability**: SystemCapability.Security.CryptoFramework.Signature 4688 4689**Parameters** 4690 4691| Name| Type | Mandatory| Description | 4692| ------ | -------- | ---- | ---------- | 4693| data | [DataBlob](#datablob) | Yes | Data to pass in.| 4694 4695**Return value** 4696 4697| Type | Description | 4698| -------------- | ------------- | 4699| void | No value is returned.| 4700 4701**Error codes** 4702For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 4703 4704| ID| Error Message | 4705| -------- | ---------------------- | 4706| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 4707| 17620001 | memory operation failed. | 4708| 17620002 | failed to convert parameters between arkts and c. | 4709| 17630001 | crypto operation error. | 4710 4711### verify 4712 4713verify(data: DataBlob | null, signatureData: DataBlob, callback: AsyncCallback\<boolean>): void 4714 4715Verifies the signature. This API uses an asynchronous callback to return the result. 4716 4717**Atomic service API**: This API can be used in atomic services since API version 12. 4718 4719**System capability**: SystemCapability.Security.CryptoFramework.Signature 4720 4721The system capability is **SystemCapability.Security.CryptoFramework** in API versions 9 to 11, and **SystemCapability.Security.CryptoFramework.Signature** since API version 12. 4722 4723**Parameters** 4724 4725| Name | Type | Mandatory| Description | 4726| ------------- | -------------------- | ---- | ---------- | 4727| 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.| 4728| signatureData | [DataBlob](#datablob) | Yes | Signature data. | 4729| callback | AsyncCallback\<boolean> | Yes | Callback used to return the signature verification result.| 4730 4731**Error codes** 4732For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 4733 4734| ID| Error Message | 4735| -------- | ---------------------- | 4736| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 4737| 17620001 | memory operation failed. | 4738| 17620002 | failed to convert parameters between arkts and c. | 4739| 17630001 | crypto operation error. | 4740 4741### verify 4742 4743verify(data: DataBlob | null, signatureData: DataBlob): Promise\<boolean> 4744 4745Verifies the signature. This API uses a promise to return the result. 4746 4747**Atomic service API**: This API can be used in atomic services since API version 12. 4748 4749**System capability**: SystemCapability.Security.CryptoFramework.Signature 4750 4751The system capability is **SystemCapability.Security.CryptoFramework** in API versions 9 to 11, and **SystemCapability.Security.CryptoFramework.Signature** since API version 12. 4752 4753**Parameters** 4754 4755| Name | Type | Mandatory| Description | 4756| ------------- | -------- | ---- | ---------- | 4757| 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.| 4758| signatureData | [DataBlob](#datablob) | Yes | Signature data. | 4759 4760**Return value** 4761 4762| Type | Description | 4763| ----------------- | ------------------------------ | 4764| Promise\<boolean> | Promise used to return the result.| 4765 4766**Error codes** 4767For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 4768 4769| ID| Error Message | 4770| -------- | ---------------------- | 4771| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 4772| 17620001 | memory operation failed. | 4773| 17620002 | failed to convert parameters between arkts and c. | 4774| 17630001 | crypto operation error. | 4775 4776### verifySync<sup>12+</sup> 4777 4778verifySync(data: DataBlob | null, signatureData: DataBlob): boolean 4779 4780Verifies the signature. This API returns the verification result synchronously. 4781 4782**Atomic service API**: This API can be used in atomic services since API version 12. 4783 4784**System capability**: SystemCapability.Security.CryptoFramework.Signature 4785 4786**Parameters** 4787 4788| Name | Type | Mandatory| Description | 4789| ------------- | -------- | ---- | ---------- | 4790| data | [DataBlob](#datablob) \| null | Yes | Data to pass in.| 4791| signatureData | [DataBlob](#datablob) | Yes | Signature data. | 4792 4793**Return value** 4794 4795| Type | Description | 4796| ----------------- | ------------------------------ | 4797| boolean | A boolean value indicating whether the signature verification is successful.| 4798 4799**Error codes** 4800For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 4801 4802| ID| Error Message | 4803| -------- | ---------------------- | 4804| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 4805| 17620001 | memory operation failed. | 4806| 17620002 | failed to convert parameters between arkts and c. | 4807| 17630001 | crypto operation error. | 4808 4809**Example (using the callback-based API)** 4810 4811For 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). 4812 4813```ts 4814import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 4815import { buffer } from '@kit.ArkTS'; 4816 4817function verifyByCallback() { 4818 let inputUpdate: cryptoFramework.DataBlob = { data: new Uint8Array(buffer.from("This is Sign test plan1", 'utf-8').buffer) }; 4819 let inputVerify: cryptoFramework.DataBlob = { data: new Uint8Array(buffer.from("This is Sign test plan2", 'utf-8').buffer) }; 4820 // 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. 4821 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]); 4822 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]); 4823 let pubKeyBlob: cryptoFramework.DataBlob = { data: pkData }; 4824 let priKeyBlob: cryptoFramework.DataBlob = { data: skData }; 4825 // The data is signData.data in Sign(). 4826 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]) } 4827 let rsaGenerator = cryptoFramework.createAsyKeyGenerator('RSA1024'); 4828 let verifyer = cryptoFramework.createVerify('RSA1024|PKCS1|SHA256'); 4829 rsaGenerator.convertKey(pubKeyBlob, priKeyBlob, (err, keyPair) => { 4830 verifyer.init(keyPair.pubKey, err => { 4831 verifyer.update(inputUpdate, err => { 4832 verifyer.verify(inputVerify, signMessageBlob, (err, res) => { 4833 console.info('verify result is ' + res); 4834 }); 4835 }); 4836 }); 4837 }); 4838} 4839``` 4840 4841**Example (using the promise-based API)** 4842 4843For more examples, see [Signing and Signature Verification with an RSA Key Pair](../../security/CryptoArchitectureKit/crypto-rsa-sign-sig-verify-pkcs1.md). 4844 4845```ts 4846import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 4847import { buffer } from '@kit.ArkTS'; 4848 4849async function genKeyPairByData(pubKeyData: Uint8Array, priKeyData: Uint8Array) { 4850 let pubKeyBlob: cryptoFramework.DataBlob = { data: pubKeyData }; 4851 let priKeyBlob: cryptoFramework.DataBlob = { data: priKeyData }; 4852 let rsaGenerator = cryptoFramework.createAsyKeyGenerator('RSA1024'); 4853 let keyPair = await rsaGenerator.convertKey(pubKeyBlob, priKeyBlob); 4854 console.info('convertKey success'); 4855 return keyPair; 4856} 4857 4858async function verifyByPromise() { 4859 // 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. 4860 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]); 4861 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]); 4862 let keyPair = await genKeyPairByData(pkData, skData); 4863 let inputUpdate: cryptoFramework.DataBlob = { data: new Uint8Array(buffer.from("This is Sign test plan1", 'utf-8').buffer) }; 4864 let inputVerify: cryptoFramework.DataBlob = { data: new Uint8Array(buffer.from("This is Sign test plan2", 'utf-8').buffer) }; 4865 // The data is signData.data in Sign(). 4866 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]) }; 4867 let verifier = cryptoFramework.createVerify('RSA1024|PKCS1|SHA256'); 4868 await verifier.init(keyPair.pubKey); 4869 await verifier.update(inputUpdate); 4870 let res = await verifier.verify(inputVerify, signMessageBlob); 4871 console.info('verify result: ' + res); 4872} 4873``` 4874 4875**Example (using the sync API)** 4876 4877For 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). 4878 4879```ts 4880import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 4881import { buffer } from '@kit.ArkTS'; 4882 4883function genKeyPairByData(pubKeyData: Uint8Array, priKeyData: Uint8Array) { 4884 let pubKeyBlob: cryptoFramework.DataBlob = { data: pubKeyData }; 4885 let priKeyBlob: cryptoFramework.DataBlob = { data: priKeyData }; 4886 let rsaGenerator = cryptoFramework.createAsyKeyGenerator('RSA1024'); 4887 let keyPair = rsaGenerator.convertKeySync(pubKeyBlob, priKeyBlob); 4888 console.info('convertKey success'); 4889 return keyPair; 4890} 4891 4892function verifyBySync() { 4893 // 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. 4894 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]); 4895 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]); 4896 let keyPair = genKeyPairByData(pkData, skData); 4897 let inputUpdate: cryptoFramework.DataBlob = { data: new Uint8Array(buffer.from("This is Sign test plan1", 'utf-8').buffer) }; 4898 let inputVerify: cryptoFramework.DataBlob = { data: new Uint8Array(buffer.from("This is Sign test plan2", 'utf-8').buffer) }; 4899 // The data is signData.data in Sign(). 4900 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]) }; 4901 let verifier = cryptoFramework.createVerify('RSA1024|PKCS1|SHA256'); 4902 verifier.initSync(keyPair.pubKey); 4903 verifier.updateSync(inputUpdate); 4904 let res = verifier.verifySync(inputVerify, signMessageBlob); 4905 console.info('verify result: ' + res); 4906} 4907``` 4908 4909### recover<sup>12+</sup> 4910 4911recover(signatureData: DataBlob): Promise\<DataBlob | null> 4912 4913Recovers the original data from a signature. This API uses a promise to return the result. 4914 4915> **NOTE** 4916> 4917> - Currently, only RSA is supported. 4918 4919**Atomic service API**: This API can be used in atomic services since API version 12. 4920 4921**System capability**: SystemCapability.Security.CryptoFramework.Signature 4922 4923**Parameters** 4924 4925| Name | Type | Mandatory| Description | 4926| ------------- | -------- | ---- | ---------- | 4927| signatureData | [DataBlob](#datablob) | Yes | Signature data. | 4928 4929**Return value** 4930 4931| Type | Description | 4932| ----------------- | ------------------------------ | 4933| Promise\<[DataBlob](#datablob) \| null> | Data restored.| 4934 4935**Error codes** 4936For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 4937 4938| ID| Error Message | 4939| -------- | ---------------------- | 4940| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 4941| 17620001 | memory operation failed. | 4942| 17620002 | failed to convert parameters between arkts and c. | 4943| 17630001 | crypto operation error. | 4944 4945**Example** 4946 4947```ts 4948import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 4949import { buffer } from '@kit.ArkTS'; 4950import { BusinessError } from '@kit.BasicServicesKit'; 4951 4952async function genKeyPairByData(pubKeyData: Uint8Array, priKeyData: Uint8Array) { 4953 let pubKeyBlob: cryptoFramework.DataBlob = { data: pubKeyData }; 4954 let priKeyBlob: cryptoFramework.DataBlob = { data: priKeyData }; 4955 let rsaGenerator = cryptoFramework.createAsyKeyGenerator('RSA1024'); 4956 let keyPair = await rsaGenerator.convertKey(pubKeyBlob, priKeyBlob); 4957 console.info('convertKey success'); 4958 return keyPair; 4959} 4960 4961async function recoverByPromise() { 4962 // 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. 4963 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]); 4964 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]); 4965 let keyPair = await genKeyPairByData(pkData, skData); 4966 // The data is signData.data in Sign(). 4967 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]) }; 4968 let verifier = cryptoFramework.createVerify('RSA1024|PKCS1|SHA256|Recover'); 4969 await verifier.init(keyPair.pubKey); 4970 try { 4971 let rawSignData = await verifier.recover(signMessageBlob); 4972 if (rawSignData != null) { 4973 console.info('[Promise]: recover result: ' + rawSignData.data); 4974 } else { 4975 console.error("[Promise]: get verify recover result fail!"); 4976 } 4977 } catch (error) { 4978 let e: BusinessError = error as BusinessError; 4979 console.error(`promise error, ${e.code}, ${e.message}`); 4980 } 4981} 4982``` 4983 4984### recoverSync<sup>12+</sup> 4985 4986recoverSync(signatureData: DataBlob): DataBlob | null 4987 4988Recovers the original data from a signature. This API returns the result synchronously. 4989 4990> **NOTE** 4991> 4992> - Currently, only RSA is supported. 4993 4994**Atomic service API**: This API can be used in atomic services since API version 12. 4995 4996**System capability**: SystemCapability.Security.CryptoFramework.Signature 4997 4998**Parameters** 4999 5000| Name | Type | Mandatory| Description | 5001| ------------- | -------- | ---- | ---------- | 5002| signatureData | [DataBlob](#datablob) | Yes | Signature data. | 5003 5004**Return value** 5005 5006| Type | Description | 5007| ----------------- | ------------------------------ | 5008| [DataBlob](#datablob) \| null | Data restored.| 5009 5010**Error codes** 5011For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 5012 5013| ID| Error Message | 5014| -------- | ---------------------- | 5015| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 5016| 17620001 | memory operation failed. | 5017| 17620002 | failed to convert parameters between arkts and c. | 5018| 17630001 | crypto operation error. | 5019 5020### setVerifySpec<sup>10+</sup> 5021 5022setVerifySpec(itemType: SignSpecItem, itemValue: number): void 5023 5024setVerifySpec(itemType: SignSpecItem, itemValue: number \| Uint8Array): void 5025 5026Sets signature verification specifications. You can use this API to set signature verification parameters that cannot be set by [createVerify](#cryptoframeworkcreateverify). 5027 5028Currently, only RSA and SM2 are supported. Since API version 11, SM2 signing parameters can be set. 5029 5030The parameters for signature verification must be the same as those for signing. 5031 5032**Atomic service API**: This API can be used in atomic services since API version 12. 5033 5034**System capability**: SystemCapability.Security.CryptoFramework.Signature 5035 5036The system capability is **SystemCapability.Security.CryptoFramework** in API versions 10 to 11, and **SystemCapability.Security.CryptoFramework.Signature** since API version 12. 5037 5038**Parameters** 5039 5040| Name | Type | Mandatory| Description | 5041| -------- | -------------------- | ---- | ---------- | 5042| itemType | [SignSpecItem](#signspecitem10) | Yes | Signature verification parameter to set.| 5043| itemValue | number \| Uint8Array<sup>11+</sup> | Yes | Value of the signature verification parameter to set.| 5044 5045**Error codes** 5046For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 5047 5048| ID| Error Message | 5049| -------- | ---------------------- | 5050| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 5051| 801 | this operation is not supported. | 5052| 17620001 | memory operation failed. | 5053| 17630001 | crypto operation error. | 5054 5055**Example** 5056 5057<!--code_no_check--> 5058```ts 5059let verifyer: cryptoFramework.Verify; // The process of generating the Verify instance is omitted here. 5060let setN = 20; 5061verifyer.setVerifySpec(cryptoFramework.SignSpecItem.PSS_SALT_LEN_NUM, setN); 5062``` 5063 5064### getVerifySpec<sup>10+</sup> 5065 5066getVerifySpec(itemType: SignSpecItem): string | number 5067 5068Obtains signature verification specifications. Currently, only RSA is supported. 5069 5070The parameters for signature verification must be the same as those for signing. 5071 5072**Atomic service API**: This API can be used in atomic services since API version 12. 5073 5074**System capability**: SystemCapability.Security.CryptoFramework.Signature 5075 5076The system capability is **SystemCapability.Security.CryptoFramework** in API versions 10 to 11, and **SystemCapability.Security.CryptoFramework.Signature** since API version 12. 5077 5078**Parameters** 5079 5080| Name| Type | Mandatory| Description | 5081| ------ | -------- | ---- | ---------- | 5082| itemType | [SignSpecItem](#signspecitem10) | Yes | Signature verification parameter to obtain.| 5083 5084**Return value** 5085 5086| Type | Description | 5087| -------------- | ----------- | 5088| string \| number | Returns the value of the parameter obtained.| 5089 5090**Error codes** 5091For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 5092 5093| ID| Error Message | 5094| -------- | ---------------------- | 5095| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 5096| 801 | this operation is not supported. | 5097| 17620001 | memory operation failed. | 5098| 17630001 | crypto operation error. | 5099 5100**Example** 5101 5102<!--code_no_check--> 5103```ts 5104let verifyer: cryptoFramework.Verify; // The process of generating the Verify instance is omitted here. 5105let saltLen = verifyer.getVerifySpec(cryptoFramework.SignSpecItem.PSS_SALT_LEN_NUM); 5106``` 5107 5108## cryptoFramework.createKeyAgreement 5109 5110createKeyAgreement(algName: string): KeyAgreement 5111 5112Creates a **KeyAgreement** instance. 5113 5114For details about the supported specifications, see [Key Agreement Overview and Algorithm Specifications](../../security/CryptoArchitectureKit/crypto-key-agreement-overview.md). 5115 5116**Atomic service API**: This API can be used in atomic services since API version 12. 5117 5118**System capability**: SystemCapability.Security.CryptoFramework.KeyAgreement 5119 5120The system capability is **SystemCapability.Security.CryptoFramework** in API versions 9 to 11, and **SystemCapability.Security.CryptoFramework.KeyAgreement** since API version 12. 5121 5122**Parameters** 5123 5124| Name | Type | Mandatory| Description | 5125| ------- | ------ | ---- | ------------------------------------------------------------ | 5126| algName | string | Yes | Key agreement algorithm to use. In addition to ECC, X25519 and DH are supported since API version 11.| 5127 5128**Return value** 5129 5130| Type | Description | 5131| ------------ | ------------------------------------------ | 5132| KeyAgreement | Returns the **KeyAgreement** instance created.| 5133 5134**Error codes** 5135For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 5136 5137| ID| Error Message | 5138| -------- | ---------------------- | 5139| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 5140| 801 | this operation is not supported. | 5141| 17620001 | memory operation failed. | 5142 5143**Example** 5144 5145```ts 5146import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 5147 5148let keyAgreement = cryptoFramework.createKeyAgreement('ECC256'); 5149``` 5150 5151## KeyAgreement 5152 5153Provides 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). 5154 5155### Attributes 5156 5157**Atomic service API**: This API can be used in atomic services since API version 12. 5158 5159**System capability**: SystemCapability.Security.CryptoFramework.KeyAgreement 5160 5161The system capability is **SystemCapability.Security.CryptoFramework** in API versions 9 to 11, and **SystemCapability.Security.CryptoFramework.KeyAgreement** since API version 12. 5162 5163| Name | Type | Read-Only| Optional| Description | 5164| ------- | ------ | ---- | ---- | ---------------------------- | 5165| algName | string | Yes | No | Algorithm used for key agreement.| 5166 5167### generateSecret 5168 5169generateSecret(priKey: PriKey, pubKey: PubKey, callback: AsyncCallback\<DataBlob>): void 5170 5171Generates a shared secret based on the given private key and public key. This API uses an asynchronous callback to return the shared secret generated. 5172 5173**Atomic service API**: This API can be used in atomic services since API version 12. 5174 5175**System capability**: SystemCapability.Security.CryptoFramework.KeyAgreement 5176 5177The system capability is **SystemCapability.Security.CryptoFramework** in API versions 9 to 11, and **SystemCapability.Security.CryptoFramework.KeyAgreement** since API version 12. 5178 5179**Parameters** 5180 5181| Name | Type | Mandatory| Description | 5182| -------- | ------------------------ | ---- | ---------------------- | 5183| priKey | [PriKey](#prikey) | Yes | Private key used for key agreement.| 5184| pubKey | [PubKey](#pubkey) | Yes | Public key used for key agreement.| 5185| callback | AsyncCallback\<[DataBlob](#datablob)> | Yes | Callback used to return the shared key.| 5186 5187**Error codes** 5188For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 5189 5190| ID| Error Message | 5191| -------- | ---------------------- | 5192| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 5193| 17620001 | memory operation failed. | 5194| 17620002 | failed to convert parameters between arkts and c. | 5195| 17630001 | crypto operation error. | 5196 5197### generateSecret 5198 5199generateSecret(priKey: PriKey, pubKey: PubKey): Promise\<DataBlob> 5200 5201Generates a shared secret based on the given private key and public key. This API uses a promise to return the shared secret generated. 5202 5203**Atomic service API**: This API can be used in atomic services since API version 12. 5204 5205**System capability**: SystemCapability.Security.CryptoFramework.KeyAgreement 5206 5207The system capability is **SystemCapability.Security.CryptoFramework** in API versions 9 to 11, and **SystemCapability.Security.CryptoFramework.KeyAgreement** since API version 12. 5208 5209**Parameters** 5210 5211| Name| Type | Mandatory| Description | 5212| ------ | ------ | ---- | ---------------------- | 5213| priKey | [PriKey](#prikey) | Yes | Private key used for key agreement.| 5214| pubKey | [PubKey](#pubkey) | Yes | Public key used for key agreement.| 5215 5216**Return value** 5217 5218| Type | Description | 5219| ------------------ | -------- | 5220| Promise\<[DataBlob](#datablob)> | Promise used to return the shared secret generated.| 5221 5222**Error codes** 5223For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 5224 5225| ID| Error Message | 5226| -------- | ---------------------- | 5227| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 5228| 17620001 | memory operation failed. | 5229| 17620002 | failed to convert parameters between arkts and c. | 5230| 17630001 | crypto operation error. | 5231 5232### generateSecretSync<sup>12+</sup> 5233 5234generateSecretSync(priKey: PriKey, pubKey: PubKey): DataBlob 5235 5236Generates a shared secret based on the given private key and public key. This API returns the shared secret generated synchronously. 5237 5238**Atomic service API**: This API can be used in atomic services since API version 12. 5239 5240**System capability**: SystemCapability.Security.CryptoFramework.KeyAgreement 5241 5242**Parameters** 5243 5244| Name| Type | Mandatory| Description | 5245| ------ | ------ | ---- | ---------------------- | 5246| priKey | [PriKey](#prikey) | Yes | Private key used for key agreement.| 5247| pubKey | [PubKey](#pubkey) | Yes | Public key used for key agreement.| 5248 5249**Return value** 5250 5251| Type | Description | 5252| ------------------ | -------- | 5253|[DataBlob](#datablob) | Promise used to return the shared secret generated.| 5254 5255**Error codes** 5256For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 5257 5258| ID| Error Message | 5259| -------- | ---------------------- | 5260| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 5261| 17620001 | memory operation failed. | 5262| 17620002 | failed to convert parameters between arkts and c. | 5263| 17630001 | crypto operation error. | 5264 5265**Example (using the callback-based API)** 5266 5267<!--code_no_check--> 5268```ts 5269import { BusinessError } from '@kit.BasicServicesKit'; 5270 5271let globalKeyPair: cryptoFramework.KeyPair; // globalKeyPair is an asymmetric key object generated by the asymmetric key generator. The generation process is omitted here. 5272let keyAgreement = cryptoFramework.createKeyAgreement('ECC256'); 5273keyAgreement.generateSecret(globalKeyPair.priKey, globalKeyPair.pubKey, (err, secret) => { 5274 if (err) { 5275 console.error("keyAgreement error."); 5276 return; 5277 } 5278 console.info('keyAgreement output is ' + secret.data); 5279}); 5280``` 5281 5282**Example (using the promise-based API)** 5283 5284<!--code_no_check--> 5285```ts 5286import { BusinessError } from '@kit.BasicServicesKit'; 5287 5288let globalKeyPair: cryptoFramework.KeyPair; // globalKeyPair is an asymmetric key object generated by the asymmetric key generator. The generation process is omitted here. 5289let keyAgreement = cryptoFramework.createKeyAgreement('ECC256'); 5290let keyAgreementPromise = keyAgreement.generateSecret(globalKeyPair.priKey, globalKeyPair.pubKey); 5291keyAgreementPromise.then(secret => { 5292 console.info('keyAgreement output is ' + secret.data); 5293}).catch((error: BusinessError) => { 5294 console.error("keyAgreement error."); 5295}); 5296``` 5297 5298**Example (using the sync API)** 5299 5300<!--code_no_check--> 5301```ts 5302let asyGenerator = cryptoFramework.CreateAsyKeyGenerator("ECC256"); 5303let globalKeyPair = asyGenerator.generateKeyPairSync(); 5304let keyAgreement = cryptoFramework.createKeyAgreement('ECC256'); 5305let secret = keyAgreement.generateSecretSync(globalKeyPair.priKey, globalKeyPair.pubKey); 5306console.info("[Sync]keyAgreement output is " + secret.data); 5307``` 5308 5309## cryptoFramework.createMd 5310 5311createMd(algName: string): Md 5312 5313Creates an **Md** instance for MD operations. 5314 5315For details about the supported specifications, see [Supported Algorithms and Specifications](../../security/CryptoArchitectureKit/crypto-generate-message-digest-overview.md#supported-algorithms-and-specifications). 5316 5317**Atomic service API**: This API can be used in atomic services since API version 12. 5318 5319**System capability**: SystemCapability.Security.CryptoFramework.MessageDigest 5320 5321The system capability is **SystemCapability.Security.CryptoFramework** in API versions 9 to 11, and **SystemCapability.Security.CryptoFramework.MessageDigest** since API version 12. 5322 5323**Parameters** 5324 5325| Name | Type | Mandatory| Description | 5326| ------- | ------ | ---- | ------------------------------------------------------------ | 5327| 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).| 5328 5329**Return value** 5330 5331| Type| Description | 5332| ---- | --------------------------------------- | 5333| Md | Returns the [Md](#md) instance created.| 5334 5335**Error codes** 5336For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 5337 5338| ID| Error Message | 5339| -------- | ------------------ | 5340| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 5341| 17620001 | memory operation failed. | 5342 5343**Example** 5344 5345```ts 5346import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 5347import { BusinessError } from '@kit.BasicServicesKit'; 5348 5349try { 5350 // Set algName based on the algorithm supported. 5351 let md = cryptoFramework.createMd('SHA256'); 5352} catch (error) { 5353 let e: BusinessError = error as BusinessError; 5354 console.error(`sync error, ${e.code}, ${e.message}`); 5355} 5356``` 5357 5358## Md 5359 5360Provides APIs for MD operations. Before using any API of the **Md** class, you must create an **Md** instance by using [createMd](#cryptoframeworkcreatemd). 5361 5362### Attributes 5363 5364**Atomic service API**: This API can be used in atomic services since API version 12. 5365 5366**System capability**: SystemCapability.Security.CryptoFramework.MessageDigest 5367 5368The system capability is **SystemCapability.Security.CryptoFramework** in API versions 9 to 11, and **SystemCapability.Security.CryptoFramework.MessageDigest** since API version 12. 5369 5370| Name | Type | Read-Only| Optional| Description | 5371| ------- | ------ | ---- | ---- | ---------------------- | 5372| algName | string | Yes | No | Digest algorithm.| 5373 5374### update 5375 5376update(input: DataBlob, callback: AsyncCallback\<void>): void 5377 5378Updates the digest status 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. 5379 5380> **NOTE** 5381> 5382> For details about the code for calling **update** multiple times in an MD operation, see [MD (Passing In Data by Segment)](../../security/CryptoArchitectureKit/crypto-generate-message-digest.md#generating-an-md-by-passing-in-data-by-segment). 5383 5384**Atomic service API**: This API can be used in atomic services since API version 12. 5385 5386**System capability**: SystemCapability.Security.CryptoFramework.MessageDigest 5387 5388The system capability is **SystemCapability.Security.CryptoFramework** in API versions 9 to 11, and **SystemCapability.Security.CryptoFramework.MessageDigest** since API version 12. 5389 5390**Differentiated device support**: This API runs properly on phones, PCs/2-in-1 devices, tablets, TVs, and wearables. However, if it is called on a lite wearable, **undefined** is returned. 5391 5392**Parameters** 5393 5394| Name | Type | Mandatory| Description | 5395| -------- | --------------------- | ---- | ------------ | 5396| input | [DataBlob](#datablob) | Yes | Data to pass in.| 5397| callback | AsyncCallback\<void> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object. | 5398 5399**Error codes** 5400For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 5401 5402| ID| Error Message | 5403| -------- | ---------------------- | 5404| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 5405| 17620001| memory operation failed. | 5406| 17630001 | crypto operation error. | 5407 5408### update 5409 5410update(input: DataBlob): Promise\<void> 5411 5412Updates the MD digest status. This API uses a promise to return the result. **update** must be used with **digest** together. **digest** is mandatory, and **update** is optional. 5413 5414> **NOTE** 5415> 5416> For details about the code for calling **update** multiple times in an MD operation, see [MD (Passing In Data by Segment)](../../security/CryptoArchitectureKit/crypto-generate-message-digest.md#generating-an-md-by-passing-in-data-by-segment). 5417 5418**Atomic service API**: This API can be used in atomic services since API version 12. 5419 5420**System capability**: SystemCapability.Security.CryptoFramework.MessageDigest 5421 5422The system capability is **SystemCapability.Security.CryptoFramework** in API versions 9 to 11, and **SystemCapability.Security.CryptoFramework.MessageDigest** since API version 12. 5423 5424**Differentiated device support**: This API runs properly on phones, PCs/2-in-1 devices, tablets, TVs, and wearables. However, if it is called on a lite wearable, **undefined** is returned. 5425 5426**Parameters** 5427 5428| Name| Type | Mandatory| Description | 5429| ------ | -------- | ---- | ------------ | 5430| input | [DataBlob](#datablob) | Yes | Data to pass in.| 5431 5432**Return value** 5433 5434| Type | Description | 5435| -------------- | ------------- | 5436| Promise\<void> | Promise that returns no value.| 5437 5438**Error codes** 5439For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 5440 5441| ID| Error Message | 5442| -------- | ---------------------- | 5443| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 5444| 17620001| memory operation failed. | 5445| 17630001 | crypto operation error. | 5446 5447### updateSync<sup>12+</sup> 5448 5449updateSync(input: DataBlob): void 5450 5451Updates the MD digest status. This API returns the result synchronously. **updateSync** must be used with **digestSync** together. **digestSync** is mandatory, and **updateSync** is optional. 5452 5453> **NOTE** 5454> 5455> For details about the code for calling **updateSync** multiple times in an MD operation, see [MD (Passing In Data by Segment)](../../security/CryptoArchitectureKit/crypto-generate-message-digest.md#generating-an-md-by-passing-in-data-by-segment). 5456 5457**Atomic service API**: This API can be used in atomic services since API version 12. 5458 5459**System capability**: SystemCapability.Security.CryptoFramework.MessageDigest 5460 5461**Parameters** 5462 5463| Name| Type | Mandatory| Description | 5464| ------ | -------- | ---- | ------------ | 5465| input | [DataBlob](#datablob) | Yes | Data to pass in.| 5466 5467**Error codes** 5468For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 5469 5470| ID| Error Message | 5471| -------- | ---------------------- | 5472| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed. | 5473| 17620001| memory operation failed. | 5474| 17630001 | crypto operation error. | 5475 5476### digest 5477 5478digest(callback: AsyncCallback\<DataBlob>): void 5479 5480Generates an MD. This API uses an asynchronous callback to return the result. 5481 5482**Atomic service API**: This API can be used in atomic services since API version 12. 5483 5484**System capability**: SystemCapability.Security.CryptoFramework.MessageDigest 5485 5486The system capability is **SystemCapability.Security.CryptoFramework** in API versions 9 to 11, and **SystemCapability.Security.CryptoFramework.MessageDigest** since API version 12. 5487 5488**Differentiated device support**: This API runs properly on phones, PCs/2-in-1 devices, tablets, TVs, and wearables. However, if it is called on a lite wearable, **undefined** is returned. 5489 5490**Parameters** 5491 5492| Name | Type | Mandatory| Description | 5493| -------- | ------------------------ | ---- | ---------- | 5494| callback | AsyncCallback\<[DataBlob](#datablob)> | Yes | Callback used to return a **DataBlob** object.| 5495 5496**Error codes** 5497For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 5498 5499 5500| ID| Error Message | 5501| -------- | ---------------------- | 5502| 17620001 | memory operation failed. | 5503| 17630001 | crypto operation error. | 5504 5505**Example** 5506 5507```ts 5508import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 5509import { buffer } from '@kit.ArkTS'; 5510 5511function mdByCallback() { 5512 let md = cryptoFramework.createMd('SHA256'); 5513 md.update({ data: new Uint8Array(buffer.from("mdTestMessage", 'utf-8').buffer) }, (err) => { 5514 md.digest((err, digestOutput) => { 5515 console.info('[Callback]: MD result: ' + digestOutput.data); 5516 console.info('[Callback]: MD len: ' + md.getMdLength()); 5517 }); 5518 }); 5519} 5520``` 5521 5522### digest 5523 5524digest(): Promise\<DataBlob> 5525 5526Generates an MD. This API uses a promise to return the result. 5527 5528**Atomic service API**: This API can be used in atomic services since API version 12. 5529 5530**System capability**: SystemCapability.Security.CryptoFramework.MessageDigest 5531 5532The system capability is **SystemCapability.Security.CryptoFramework** in API versions 9 to 11, and **SystemCapability.Security.CryptoFramework.MessageDigest** since API version 12. 5533 5534**Differentiated device support**: This API runs properly on phones, PCs/2-in-1 devices, tablets, TVs, and wearables. However, if it is called on a lite wearable, **undefined** is returned. 5535 5536**Return value** 5537 5538| Type | Description | 5539| ------------------ | ----------- | 5540| Promise\<[DataBlob](#datablob)> | Promise used to return the result.| 5541 5542**Error codes** 5543For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 5544 5545| ID| Error Message | 5546| -------- | ---------------------- | 5547| 17620001 | memory operation failed. | 5548| 17630001 | crypto operation error. | 5549 5550**Example** 5551 5552```ts 5553import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 5554import { buffer } from '@kit.ArkTS'; 5555 5556async function mdByPromise() { 5557 let md = cryptoFramework.createMd('SHA256'); 5558 await md.update({ data: new Uint8Array(buffer.from("mdTestMessage", 'utf-8').buffer) }); 5559 let mdOutput = await md.digest(); 5560 console.info('[Promise]: MD result: ' + mdOutput.data); 5561 console.info('[Promise]: MD len: ' + md.getMdLength()); 5562} 5563``` 5564 5565### digestSync<sup>12+</sup> 5566 5567digestSync(): DataBlob 5568 5569Generates an MD. This API returns the result synchronously. 5570 5571**Atomic service API**: This API can be used in atomic services since API version 12. 5572 5573**System capability**: SystemCapability.Security.CryptoFramework.MessageDigest 5574 5575**Return value** 5576 5577| Type | Description | 5578| ------------------ | ----------- | 5579| [DataBlob](#datablob) | MD generated.| 5580 5581**Error codes** 5582For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 5583 5584| ID| Error Message | 5585| -------- | ---------------------- | 5586| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed. | 5587| 17620001 | memory operation failed. | 5588| 17620002 | failed to convert parameters between arkts and c. | 5589| 17630001 | crypto operation error. | 5590 5591**Example** 5592 5593```ts 5594import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 5595import { buffer } from '@kit.ArkTS'; 5596 5597async function mdBySync() { 5598 let md = cryptoFramework.createMd('SHA256'); 5599 md.updateSync({ data: new Uint8Array(buffer.from("mdTestMessage", 'utf-8').buffer) }); 5600 let mdOutput = md.digestSync(); 5601 console.info('[Sync]: MD result: ' + mdOutput.data); 5602 console.info('[Sync]: MD len: ' + md.getMdLength()); 5603} 5604``` 5605 5606### getMdLength 5607 5608getMdLength(): number 5609 5610Obtains the MD length, in bytes. 5611 5612**Atomic service API**: This API can be used in atomic services since API version 12. 5613 5614**System capability**: SystemCapability.Security.CryptoFramework.MessageDigest 5615 5616The system capability is **SystemCapability.Security.CryptoFramework** in API versions 9 to 11, and **SystemCapability.Security.CryptoFramework.MessageDigest** since API version 12. 5617 5618**Return value** 5619 5620| Type | Description | 5621| ------ | -------------------------- | 5622| number | MD length obtained.| 5623 5624**Error codes** 5625For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 5626 5627| ID| Error Message | 5628| -------- | ---------------------- | 5629| 17630001 | crypto operation error. | 5630 5631**Example** 5632 5633```ts 5634import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 5635 5636function getLength() { 5637 let md = cryptoFramework.createMd('SHA256'); 5638 console.info('[Promise]: MD len: ' + md.getMdLength()); 5639} 5640``` 5641 5642## cryptoFramework.createMac 5643 5644createMac(algName: string): Mac 5645 5646Creates a **Mac** instance for MAC operations. 5647 5648For details about the supported specifications, see [MAC Overview and Algorithm Specifications](../../security/CryptoArchitectureKit/crypto-compute-mac-overview.md). 5649 5650**Atomic service API**: This API can be used in atomic services since API version 12. 5651 5652**System capability**: SystemCapability.Security.CryptoFramework.Mac 5653 5654The system capability is **SystemCapability.Security.CryptoFramework** in API versions 9 to 11, and **SystemCapability.Security.CryptoFramework.Mac** since API version 12. 5655 5656**Parameters** 5657 5658| Name | Type | Mandatory| Description | 5659| ------- | ------ | ---- | ------------------------------------------------------------ | 5660| algName | string | Yes | Specifies the digest algorithm. For details about the supported algorithms, see [MAC Overview and Algorithm Specifications](../../security/CryptoArchitectureKit/crypto-compute-mac-overview.md).| 5661 5662**Return value** 5663 5664| Type| Description | 5665| ---- | ----------------------------------------- | 5666| Mac | Returns the [Mac](#mac) instance created.| 5667 5668**Error codes** 5669For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 5670 5671| ID| Error Message | 5672| -------- | ------------------ | 5673| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 5674| 17620001 | memory operation failed. | 5675 5676**Example** 5677 5678```ts 5679import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 5680import { BusinessError } from '@kit.BasicServicesKit'; 5681 5682try { 5683 // Set algName based on the algorithm supported. 5684 let mac = cryptoFramework.createMac('SHA256'); 5685} catch (error) { 5686 let e: BusinessError = error as BusinessError; 5687 console.error(`sync error, ${e.code}, ${e.message}`); 5688} 5689``` 5690 5691## cryptoFramework.createMac<sup>18+</sup> 5692 5693createMac(macSpec: MacSpec): Mac 5694 5695Creates a **Mac** instance for message authentication code (MAC) operations. 5696 5697For details about the supported specifications, see [MAC Overview and Algorithm Specifications](../../security/CryptoArchitectureKit/crypto-compute-mac-overview.md). 5698 5699**Atomic service API**: This API can be used in atomic services since API version 18. 5700 5701**System capability**: SystemCapability.Security.CryptoFramework.Mac 5702 5703**Parameters** 5704 5705| Name | Type | Mandatory| Description | 5706| ------- | ------ | ---- | ------------------------------------------------------------ | 5707| macSpec | [MacSpec](#macspec18) | Yes | Specifies the input parameter struct based on the MAC algorithm. For details about the supported algorithms, see [MAC Overview and Algorithm Specifications](../../security/CryptoArchitectureKit/crypto-compute-mac-overview.md).| 5708 5709**Return value** 5710 5711| Type| Description | 5712| ---- | ----------------------------------------- | 5713| Mac | [Mac](#mac) instance created.| 5714 5715**Error codes** 5716For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 5717 5718| ID| Error Message | 5719| -------- | ------------------ | 5720| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 5721| 17620001 | memory operation failed. | 5722| 17620002 | failed to convert parameters between arkts and c. | 5723| 17630001 | crypto operation error. | 5724 5725**Example** 5726 5727```ts 5728import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 5729import { BusinessError } from '@kit.BasicServicesKit'; 5730 5731try { 5732 // Set algName based on the algorithm supported. 5733 let spec: cryptoFramework.HmacSpec = { 5734 algName: "HMAC", 5735 mdName: "SHA256", 5736 }; 5737 let mac = cryptoFramework.createMac(spec); 5738} catch (error) { 5739 let e: BusinessError = error as BusinessError; 5740 console.error(`sync error, ${e.code}, ${e.message}`); 5741} 5742``` 5743 5744## Mac 5745 5746Provides APIs for MAC operations. Before using any API of the **Mac** class, you must create a **Mac** instance by using [createMac](#cryptoframeworkcreatemac). 5747 5748### Attributes 5749 5750**Atomic service API**: This API can be used in atomic services since API version 12. 5751 5752**System capability**: SystemCapability.Security.CryptoFramework.Mac 5753 5754The system capability is **SystemCapability.Security.CryptoFramework** in API versions 9 to 11, and **SystemCapability.Security.CryptoFramework.Mac** since API version 12. 5755 5756| Name | Type | Read-Only| Optional| Description | 5757| ------- | ------ | ---- | ---- | ---------------------- | 5758| algName | string | Yes | No | Digest algorithm.| 5759 5760### init 5761 5762init(key: SymKey, callback: AsyncCallback\<void>): void 5763 5764Initializes 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. 5765 5766 > **NOTE** 5767 > 5768 > 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. 5769 5770**Atomic service API**: This API can be used in atomic services since API version 12. 5771 5772**System capability**: SystemCapability.Security.CryptoFramework.Mac 5773 5774The system capability is **SystemCapability.Security.CryptoFramework** in API versions 9 to 11, and **SystemCapability.Security.CryptoFramework.Mac** since API version 12. 5775 5776**Parameters** 5777 5778| Name | Type | Mandatory| Description | 5779| -------- | -------------------- | ---- | -------------- | 5780| key | [SymKey](#symkey) | Yes | Symmetric key obtained.| 5781| callback | AsyncCallback\<void> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object. | 5782 5783**Error codes** 5784For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 5785 5786| ID| Error Message | 5787| -------- | ---------------------- | 5788| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 5789| 17620001| memory operation failed. | 5790| 17630001 | crypto operation error. | 5791 5792### init 5793 5794init(key: SymKey): Promise\<void> 5795 5796Initializes 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. 5797 5798**Atomic service API**: This API can be used in atomic services since API version 12. 5799 5800**System capability**: SystemCapability.Security.CryptoFramework.Mac 5801 5802The system capability is **SystemCapability.Security.CryptoFramework** in API versions 9 to 11, and **SystemCapability.Security.CryptoFramework.Mac** since API version 12. 5803 5804**Parameters** 5805 5806| Name| Type | Mandatory| Description | 5807| ------ | ------ | ---- | ------------ | 5808| key | [SymKey](#symkey) | Yes | Symmetric key obtained.| 5809 5810**Return value** 5811 5812| Type | Description | 5813| -------------- | ------------- | 5814| Promise\<void> | Promise that returns no value.| 5815 5816**Error codes** 5817For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 5818 5819| ID| Error Message | 5820| -------- | ---------------------- | 5821| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 5822| 17620001| memory operation failed. | 5823| 17630001 | crypto operation error. | 5824 5825### initSync<sup>12+</sup> 5826 5827initSync(key: SymKey): void 5828 5829Initializes 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. 5830 5831**Atomic service API**: This API can be used in atomic services since API version 12. 5832 5833**System capability**: SystemCapability.Security.CryptoFramework.Mac 5834 5835**Parameters** 5836 5837| Name| Type | Mandatory| Description | 5838| ------ | ------ | ---- | ------------ | 5839| key | [SymKey](#symkey) | Yes | Symmetric key obtained.| 5840 5841**Error codes** 5842For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 5843 5844| ID| Error Message | 5845| -------- | ---------------------- | 5846| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed. | 5847| 17620001| memory operation failed. | 5848| 17630001 | crypto operation error. | 5849 5850### update 5851 5852update(input: DataBlob, callback: AsyncCallback\<void>): void 5853 5854Updates the MAC status. This API uses a callback to return the result. 5855 5856> **NOTE** 5857> 5858> 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). 5859 5860**Atomic service API**: This API can be used in atomic services since API version 12. 5861 5862**System capability**: SystemCapability.Security.CryptoFramework.Mac 5863 5864The system capability is **SystemCapability.Security.CryptoFramework** in API versions 9 to 11, and **SystemCapability.Security.CryptoFramework.Mac** since API version 12. 5865 5866**Parameters** 5867 5868| Name | Type | Mandatory| Description | 5869| -------- | --------------------- | ---- | ------------ | 5870| input | [DataBlob](#datablob) | Yes | Data to pass in.| 5871| callback | AsyncCallback\<void> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.| 5872 5873**Error codes** 5874For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 5875 5876| ID| Error Message | 5877| -------- | ---------------------- | 5878| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 5879| 17620001| memory operation failed. | 5880| 17630001 | crypto operation error. | 5881 5882### update 5883 5884update(input: DataBlob): Promise\<void> 5885 5886Updates the MAC status. This API uses a promise to return the result. 5887 5888> **NOTE** 5889> 5890> 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). 5891 5892**Atomic service API**: This API can be used in atomic services since API version 12. 5893 5894**System capability**: SystemCapability.Security.CryptoFramework.Mac 5895 5896The system capability is **SystemCapability.Security.CryptoFramework** in API versions 9 to 11, and **SystemCapability.Security.CryptoFramework.Mac** since API version 12. 5897 5898**Parameters** 5899 5900| Name| Type | Mandatory| Description | 5901| ------ | -------- | ---- | ---------- | 5902| input | [DataBlob](#datablob) | Yes | Data to pass in.| 5903 5904**Return value** 5905 5906| Type | Description | 5907| -------------- | ------------- | 5908| Promise\<void> | Promise that returns no value.| 5909 5910**Error codes** 5911For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 5912 5913| ID| Error Message | 5914| -------- | ---------------------- | 5915| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 5916| 17620001| memory operation failed. | 5917| 17630001 | crypto operation error. | 5918 5919### updateSync<sup>12+</sup> 5920 5921updateSync(input: DataBlob): void 5922 5923Updates the MAC status. This API returns the result synchronously. 5924 5925> **NOTE** 5926> 5927> 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). 5928 5929**Atomic service API**: This API can be used in atomic services since API version 12. 5930 5931**System capability**: SystemCapability.Security.CryptoFramework.Mac 5932 5933**Parameters** 5934 5935| Name| Type | Mandatory| Description | 5936| ------ | -------- | ---- | ---------- | 5937| input | [DataBlob](#datablob) | Yes | Data to pass in.| 5938 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| 17620001| memory operation failed. | 5947| 17630001 | crypto operation error. | 5948 5949### doFinal 5950 5951doFinal(callback: AsyncCallback\<DataBlob>): void 5952 5953Finishes the MAC computation. This API uses an asynchronous callback to return the result. 5954 5955**Atomic service API**: This API can be used in atomic services since API version 12. 5956 5957**System capability**: SystemCapability.Security.CryptoFramework.Mac 5958 5959The system capability is **SystemCapability.Security.CryptoFramework** in API versions 9 to 11, and **SystemCapability.Security.CryptoFramework.Mac** since API version 12. 5960 5961**Parameters** 5962 5963| Name | Type | Mandatory| Description | 5964| -------- | ------------------------ | ---- | -------- | 5965| callback | AsyncCallback\<[DataBlob](#datablob)> | Yes | Callback used to return a **DataBlob** object.| 5966 5967**Error codes** 5968For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 5969 5970| ID| Error Message | 5971| -------- | ---------------------- | 5972| 17620001 | memory operation failed. | 5973| 17630001 | crypto operation error. | 5974 5975**Example** 5976 5977For 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). 5978 5979```ts 5980import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 5981import { buffer } from '@kit.ArkTS'; 5982 5983function hmacByCallback() { 5984 let mac = cryptoFramework.createMac('SHA256'); 5985 let keyBlob: cryptoFramework.DataBlob = { data: new Uint8Array(buffer.from("12345678abcdefgh", 'utf-8').buffer) }; 5986 let symKeyGenerator = cryptoFramework.createSymKeyGenerator('AES128'); 5987 symKeyGenerator.convertKey(keyBlob, (err, symKey) => { 5988 mac.init(symKey, (err) => { 5989 mac.update({ data: new Uint8Array(buffer.from("hmacTestMessage", 'utf-8').buffer) }, (err) => { 5990 mac.doFinal((err, output) => { 5991 console.info('[Callback]: HMAC result: ' + output.data); 5992 console.info('[Callback]: MAC len: ' + mac.getMacLength()); 5993 }); 5994 }); 5995 }); 5996 }); 5997} 5998``` 5999 6000### doFinal 6001 6002doFinal(): Promise\<DataBlob> 6003 6004Finishes the MAC computation. This API uses a promise to return the result. 6005 6006**Atomic service API**: This API can be used in atomic services since API version 12. 6007 6008**System capability**: SystemCapability.Security.CryptoFramework.Mac 6009 6010The system capability is **SystemCapability.Security.CryptoFramework** in API versions 9 to 11, and **SystemCapability.Security.CryptoFramework.Mac** since API version 12. 6011 6012**Return value** 6013 6014| Type | Description | 6015| ------------------ | ----------- | 6016| Promise\<[DataBlob](#datablob)> | Promise used to return the result.| 6017 6018**Error codes** 6019For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 6020 6021| ID| Error Message | 6022| -------- | ---------------------- | 6023| 17620001 | memory operation failed. | 6024| 17630001 | crypto operation error. | 6025 6026**Example** 6027 6028For 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). 6029 6030```ts 6031import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 6032import { buffer } from '@kit.ArkTS'; 6033 6034async function hmacByPromise() { 6035 let mac = cryptoFramework.createMac('SHA256'); 6036 let keyBlob: cryptoFramework.DataBlob = { data: new Uint8Array(buffer.from("12345678abcdefgh", 'utf-8').buffer) }; 6037 let symKeyGenerator = cryptoFramework.createSymKeyGenerator('AES128'); 6038 let symKey = await symKeyGenerator.convertKey(keyBlob); 6039 await mac.init(symKey); 6040 await mac.update({ data: new Uint8Array(buffer.from("hmacTestMessage", 'utf-8').buffer) }); 6041 let macOutput = await mac.doFinal(); 6042 console.info('[Promise]: HMAC result: ' + macOutput.data); 6043 console.info('[Promise]: MAC len: ' + mac.getMacLength()); 6044} 6045``` 6046 6047### doFinalSync<sup>12+</sup> 6048 6049doFinalSync(): DataBlob 6050 6051Finishes the MAC computation. This API returns the result synchronously. 6052 6053**Atomic service API**: This API can be used in atomic services since API version 12. 6054 6055**System capability**: SystemCapability.Security.CryptoFramework.Mac 6056 6057**Return value** 6058 6059| Type | Description | 6060| ------------------ | ----------- | 6061| [DataBlob](#datablob) | MAC computation result.| 6062 6063**Error codes** 6064For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 6065 6066| ID| Error Message | 6067| -------- | ---------------------- | 6068| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed. | 6069| 17620001 | memory operation failed. | 6070| 17620002 | failed to convert parameters between arkts and c. | 6071| 17630001 | crypto operation error. | 6072 6073**Example** 6074 6075For 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). 6076 6077```ts 6078import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 6079import { buffer } from '@kit.ArkTS'; 6080 6081function hmacBySync() { 6082 let mac = cryptoFramework.createMac('SHA256'); 6083 let keyBlob: cryptoFramework.DataBlob = { data: new Uint8Array(buffer.from("12345678abcdefgh", 'utf-8').buffer) }; 6084 let symKeyGenerator = cryptoFramework.createSymKeyGenerator('AES128'); 6085 let symKey = symKeyGenerator.convertKeySync(keyBlob); 6086 mac.initSync(symKey); 6087 mac.updateSync({ data: new Uint8Array(buffer.from("hmacTestMessage", 'utf-8').buffer) }); 6088 let macOutput = mac.doFinalSync(); 6089 console.info('[Sync]: HMAC result: ' + macOutput.data); 6090 console.info('[Sync]: MAC len: ' + mac.getMacLength()); 6091} 6092``` 6093 6094### getMacLength 6095 6096getMacLength(): number 6097 6098Obtains the MAC length, in bytes. 6099 6100**Atomic service API**: This API can be used in atomic services since API version 12. 6101 6102**System capability**: SystemCapability.Security.CryptoFramework.Mac 6103 6104The system capability is **SystemCapability.Security.CryptoFramework** in API versions 9 to 11, and **SystemCapability.Security.CryptoFramework.Mac** since API version 12. 6105 6106**Return value** 6107 6108| Type | Description | 6109| ------ | --------------------------- | 6110| number | MAC length obtained.| 6111 6112**Error codes** 6113For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 6114 6115| ID| Error Message | 6116| -------- | ---------------------- | 6117| 17630001 | crypto operation error. | 6118 6119**Example** 6120 6121<!--code_no_check--> 6122```ts 6123import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 6124import { BusinessError } from '@kit.BasicServicesKit'; 6125 6126let mac = cryptoFramework.createMac('SHA256'); 6127console.info('Mac algName is: ' + mac.algName); 6128let keyData = new Uint8Array([83, 217, 231, 76, 28, 113, 23, 219, 250, 71, 209, 210, 205, 97, 32, 159]); 6129let keyBlob: cryptoFramework.DataBlob = { data: keyData }; 6130let symKeyGenerator = cryptoFramework.createSymKeyGenerator('AES128'); 6131let promiseConvertKey = symKeyGenerator.convertKey(keyBlob); 6132promiseConvertKey.then(symKey => { 6133 let promiseMacInit = mac.init(symKey); 6134 return promiseMacInit; 6135}).then(() => { 6136 let blob: cryptoFramework.DataBlob = { data : new Uint8Array([83])}; 6137 let promiseMacUpdate = mac.update(blob); 6138 return promiseMacUpdate; 6139}).then(() => { 6140 let promiseMacDoFinal = mac.doFinal(); 6141 return promiseMacDoFinal; 6142}).then(macOutput => { 6143 console.info('[Promise]: HMAC result: ' + macOutput.data); 6144 let macLen = mac.getMacLength(); 6145 console.info('MAC len: ' + macLen); 6146}).catch((error: BusinessError) => { 6147 console.error("[Promise]: error: " + error.message); 6148}); 6149``` 6150 6151## cryptoFramework.createRandom 6152 6153createRandom(): Random 6154 6155Creates a **Random** instance for generating random numbers and setting seeds. 6156 6157For details about the supported specifications, see [Supported Algorithms and Specifications](../../security/CryptoArchitectureKit/crypto-generate-random-number.md#supported-algorithms-and-specifications). 6158 6159**Atomic service API**: This API can be used in atomic services since API version 11. 6160 6161**System capability**: SystemCapability.Security.CryptoFramework.Rand 6162 6163The system capability is **SystemCapability.Security.CryptoFramework** in API versions 9 to 11, and **SystemCapability.Security.CryptoFramework.Rand** since API version 12. 6164 6165**Return value** 6166 6167| Type | Description | 6168| ------ | ----------------------------------------------- | 6169| [Random](#random) | Returns the [Random](#random) instance created.| 6170 6171**Error codes** 6172For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 6173 6174| ID| Error Message | 6175| -------- | ------------ | 6176| 17620001 | memory operation failed. | 6177 6178**Example** 6179 6180```ts 6181import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 6182import { BusinessError } from '@kit.BasicServicesKit'; 6183 6184try { 6185 let rand = cryptoFramework.createRandom(); 6186} catch (error) { 6187 let e: BusinessError = error as BusinessError; 6188 console.error(`sync error, ${e.code}, ${e.message}`); 6189} 6190``` 6191 6192## Random 6193 6194Provides 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). 6195 6196### Attributes 6197 6198**Atomic service API**: This API can be used in atomic services since API version 11. 6199 6200**System capability**: SystemCapability.Security.CryptoFramework.Rand 6201 6202The system capability is **SystemCapability.Security.CryptoFramework** in API versions 9 to 11, and **SystemCapability.Security.CryptoFramework.Rand** since API version 12. 6203 6204| Name | Type | Read-Only| Optional| Description | 6205| ------- | ------ | ---- | ---- | -------------------- | 6206| algName<sup>10+</sup> | string | Yes | No | Algorithm used to generate the random number. Currently, only **CTR_DRBG** is supported.| 6207 6208### generateRandom 6209 6210generateRandom(len: number, callback: AsyncCallback\<DataBlob>): void 6211 6212Generates a random number of the specified length. This API uses an asynchronous callback to return the result. 6213 6214**Atomic service API**: This API can be used in atomic services since API version 11. 6215 6216**System capability**: SystemCapability.Security.CryptoFramework.Rand 6217 6218The system capability is **SystemCapability.Security.CryptoFramework** in API versions 9 to 11, and **SystemCapability.Security.CryptoFramework.Rand** since API version 12. 6219 6220**Differentiated device support**: This API runs properly on phones, PCs/2-in-1 devices, tablets, TVs, and wearables. However, if it is called on a lite wearable, **undefined** is returned. 6221 6222**Parameters** 6223 6224| Name | Type | Mandatory| Description | 6225| -------- | ------------------------ | ---- | -------------------- | 6226| len | number | Yes | Length of the random number to generate, in bytes. The value range is [1, INT_MAX].| 6227| callback | AsyncCallback\<[DataBlob](#datablob)> | Yes | Callback used to return a **DataBlob** object.| 6228 6229**Error codes** 6230For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 6231 6232| ID| Error Message | 6233| -------- | ---------------------- | 6234| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 6235| 17620001 | memory operation failed. | 6236| 17630001 | crypto operation error. | 6237 6238**Example** 6239 6240```ts 6241import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 6242 6243let rand = cryptoFramework.createRandom(); 6244rand.generateRandom(12, (err, randData) => { 6245 if (err) { 6246 console.error("[Callback] err: " + err.code); 6247 } else { 6248 console.info('[Callback]: generate random result: ' + randData.data); 6249 } 6250}); 6251``` 6252 6253### generateRandom 6254 6255generateRandom(len: number): Promise\<DataBlob> 6256 6257Generates a random number of the specified length. This API uses a promise to return the result. 6258 6259**Atomic service API**: This API can be used in atomic services since API version 11. 6260 6261**System capability**: SystemCapability.Security.CryptoFramework.Rand 6262 6263The system capability is **SystemCapability.Security.CryptoFramework** in API versions 9 to 11, and **SystemCapability.Security.CryptoFramework.Rand** since API version 12. 6264 6265**Differentiated device support**: This API runs properly on phones, PCs/2-in-1 devices, tablets, TVs, and wearables. However, if it is called on a lite wearable, **undefined** is returned. 6266 6267**Parameters** 6268 6269| Name| Type | Mandatory| Description | 6270| ------ | ------ | ---- | ------------------------------------------------------ | 6271| len | number | Yes | Length of the random number to generate, in bytes. The value range is [1, INT_MAX].| 6272 6273**Return value** 6274 6275| Type | Description | 6276| ------------------ | ----------- | 6277| Promise\<[DataBlob](#datablob)> | Promise used to return the result.| 6278 6279**Error codes** 6280For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 6281 6282| ID| Error Message | 6283| -------- | ---------------------- | 6284| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 6285| 17620001 | memory operation failed. | 6286| 17630001 | crypto operation error. | 6287 6288**Example** 6289 6290```ts 6291import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 6292import { BusinessError } from '@kit.BasicServicesKit'; 6293 6294let rand = cryptoFramework.createRandom(); 6295let promiseGenerateRand = rand.generateRandom(12); 6296promiseGenerateRand.then(randData => { 6297 console.info('[Promise]: rand result: ' + randData.data); 6298}).catch((error: BusinessError) => { 6299 console.error("[Promise]: error: " + error.message); 6300}); 6301``` 6302 6303### generateRandomSync<sup>10+</sup> 6304 6305generateRandomSync(len: number): DataBlob 6306 6307Generates a random number of the specified length. This API returns the result synchronously. 6308 6309**Atomic service API**: This API can be used in atomic services since API version 11. 6310 6311**System capability**: SystemCapability.Security.CryptoFramework.Rand 6312 6313The system capability is **SystemCapability.Security.CryptoFramework** in API versions 10 to 11, and **SystemCapability.Security.CryptoFramework.Rand** since API version 12. 6314 6315**Parameters** 6316 6317| Name| Type | Mandatory| Description | 6318| ------ | ------ | ---- | -------------------- | 6319| len | number | Yes | Length of the random number to generate, in bytes. The value range is [1, INT_MAX].| 6320 6321**Return value** 6322 6323| Type | Description | 6324| ------------------ | ----------- | 6325|[DataBlob](#datablob) | Returns the generated random number.| 6326 6327**Error codes** 6328For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 6329 6330| ID| Error Message | 6331| -------- | ---------------------- | 6332| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 6333| 17620001 | memory operation failed. | 6334| 17630001 | crypto operation error. | 6335 6336**Example** 6337 6338```ts 6339import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 6340import { BusinessError } from '@kit.BasicServicesKit'; 6341 6342let rand = cryptoFramework.createRandom(); 6343try { 6344 let randData = rand.generateRandomSync(12); 6345 if (randData != null) { 6346 console.info('[Sync]: rand result: ' + randData.data); 6347 } else { 6348 console.error("[Sync]: get rand result fail!"); 6349 } 6350} catch (error) { 6351 let e: BusinessError = error as BusinessError; 6352 console.error(`sync error, ${e.code}, ${e.message}`); 6353} 6354``` 6355 6356### setSeed 6357 6358setSeed(seed: DataBlob): void 6359 6360Sets a seed. 6361 6362**Atomic service API**: This API can be used in atomic services since API version 11. 6363 6364**System capability**: SystemCapability.Security.CryptoFramework.Rand 6365 6366The system capability is **SystemCapability.Security.CryptoFramework** in API versions 9 to 11, and **SystemCapability.Security.CryptoFramework.Rand** since API version 12. 6367 6368**Parameters** 6369 6370| Name| Type | Mandatory| Description | 6371| ------ | -------- | ---- | ------------ | 6372| seed | [DataBlob](#datablob) | Yes | Seed to set.| 6373 6374**Error codes** 6375For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 6376 6377| ID| Error Message | 6378| -------- | ----------------- | 6379| 17620001 | memory operation failed. | 6380 6381**Example** 6382 6383```ts 6384import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 6385import { BusinessError } from '@kit.BasicServicesKit'; 6386 6387let rand = cryptoFramework.createRandom(); 6388rand.generateRandom(12, (err, randData) => { 6389 if (err) { 6390 console.error("[Callback] err: " + err.code); 6391 } else { 6392 console.info('[Callback]: generate random result: ' + randData.data); 6393 try { 6394 rand.setSeed(randData); 6395 } catch (error) { 6396 let e: BusinessError = error as BusinessError; 6397 console.error(`sync error, ${e.code}, ${e.message}`); 6398 } 6399 } 6400}); 6401``` 6402 6403## cryptoFramework.createKdf<sup>11+</sup> 6404 6405createKdf(algName: string): Kdf 6406 6407Creates 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). 6408 6409**Atomic service API**: This API can be used in atomic services since API version 12. 6410 6411**System capability**: SystemCapability.Security.CryptoFramework.Kdf 6412 6413The system capability is **SystemCapability.Security.CryptoFramework** in API version 11, and **SystemCapability.Security.CryptoFramework.Kdf** since API version 12. 6414 6415**Parameters** 6416 6417| Name | Type | Mandatory| Description | 6418| ------- | ------ | ---- | --------------------------------- | 6419| 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**.| 6420 6421**Return value** 6422 6423| Type | Description | 6424| ------------ | ------------------------------------------ | 6425| [Kdf](#kdf11) | Key derivation function instance created.| 6426 6427**Error codes** 6428For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 6429 6430| ID| Error Message | 6431| -------- | ---------------------- | 6432| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 6433| 801 | this operation is not supported. | 6434| 17620001 | memory operation failed. | 6435 6436**Example** 6437- PBKDF2 6438```ts 6439import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 6440 6441let kdf = cryptoFramework.createKdf('PBKDF2|SHA256'); 6442``` 6443 6444## Kdf<sup>11+</sup> 6445 6446Defines 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**. 6447 6448### Attributes 6449 6450**Atomic service API**: This API can be used in atomic services since API version 12. 6451 6452**System capability**: SystemCapability.Security.CryptoFramework.Kdf 6453 6454The system capability is **SystemCapability.Security.CryptoFramework** in API version 11, and **SystemCapability.Security.CryptoFramework.Kdf** since API version 12. 6455 6456| Name | Type | Read-Only| Optional| Description | 6457| ------- | ------ | ---- | ---- | ---------------------------- | 6458| algName | string | Yes | No | Algorithm of the key derivation function.| 6459 6460### generateSecret<sup>11+</sup> 6461 6462generateSecret(params: KdfSpec, callback: AsyncCallback\<DataBlob>): void 6463 6464Generates a key based on the specified key derivation parameters. This API uses an asynchronous callback to return the result. 6465 6466**Atomic service API**: This API can be used in atomic services since API version 12. 6467 6468**System capability**: SystemCapability.Security.CryptoFramework.Kdf 6469 6470The system capability is **SystemCapability.Security.CryptoFramework** in API version 11, and **SystemCapability.Security.CryptoFramework.Kdf** since API version 12. 6471 6472**Parameters** 6473 6474| Name | Type | Mandatory| Description | 6475| -------- | ------------------------ | ---- | ---------------------- | 6476| params | [KdfSpec](#kdfspec11) | Yes | Parameters of the key derivation function.| 6477| callback | AsyncCallback\<[DataBlob](#datablob)> | Yes | Callback used to return the derived key generated.| 6478 6479**Error codes** 6480For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 6481 6482| ID| Error Message | 6483| -------- | ---------------------- | 6484| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 6485| 17620001 | memory operation failed. | 6486| 17630001 | crypto operation error. | 6487 6488**Example** 6489 6490- PBKDF2 6491 ```ts 6492 import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 6493 6494 let spec: cryptoFramework.PBKDF2Spec = { 6495 algName: 'PBKDF2', 6496 password: '123456', 6497 salt: new Uint8Array(16), 6498 iterations: 10000, 6499 keySize: 32 6500 }; 6501 let kdf = cryptoFramework.createKdf('PBKDF2|SHA256'); 6502 kdf.generateSecret(spec, (err, secret) => { 6503 if (err) { 6504 console.error("key derivation error."); 6505 return; 6506 } 6507 console.info('key derivation output is ' + secret.data); 6508 }); 6509 ``` 6510 6511- HKDF 6512 ```ts 6513 import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 6514 6515 let spec: cryptoFramework.HKDFSpec = { 6516 algName: 'HKDF', 6517 key: '123456', 6518 salt: new Uint8Array(16), 6519 info: new Uint8Array(16), 6520 keySize: 32 6521 }; 6522 let kdf = cryptoFramework.createKdf('HKDF|SHA256|EXTRACT_AND_EXPAND'); 6523 kdf.generateSecret(spec, (err, secret) => { 6524 if (err) { 6525 console.error("key derivation error."); 6526 return; 6527 } 6528 console.info('key derivation output is ' + secret.data); 6529 }); 6530 ``` 6531 6532### generateSecret<sup>11+</sup> 6533 6534generateSecret(params: KdfSpec): Promise\<DataBlob> 6535 6536Generates a key based on the specified key derivation parameters. This API uses a promise to return the result. 6537 6538**Atomic service API**: This API can be used in atomic services since API version 12. 6539 6540**System capability**: SystemCapability.Security.CryptoFramework.Kdf 6541 6542The system capability is **SystemCapability.Security.CryptoFramework** in API version 11, and **SystemCapability.Security.CryptoFramework.Kdf** since API version 12. 6543 6544**Parameters** 6545 6546| Name| Type | Mandatory| Description | 6547| ------ | ------ | ---- | ---------------------- | 6548| params | [KdfSpec](#kdfspec11) | Yes | Parameters of the key derivation function.| 6549 6550**Return value** 6551 6552| Type | Description | 6553| ------------------ | -------- | 6554| Promise\<[DataBlob](#datablob)> | Promise used to return the derived key generated.| 6555 6556**Error codes** 6557For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 6558 6559| ID| Error Message | 6560| -------- | ---------------------- | 6561| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed.| 6562| 17620001 | memory operation failed. | 6563| 17630001 | crypto operation error. | 6564 6565**Example** 6566 6567- PBKDF2 6568 ```ts 6569 import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 6570 import { BusinessError } from '@kit.BasicServicesKit'; 6571 6572 let spec: cryptoFramework.PBKDF2Spec = { 6573 algName: 'PBKDF2', 6574 password: '123456', 6575 salt: new Uint8Array(16), 6576 iterations: 10000, 6577 keySize: 32 6578 }; 6579 let kdf = cryptoFramework.createKdf('PBKDF2|SHA256'); 6580 let kdfPromise = kdf.generateSecret(spec); 6581 kdfPromise.then(secret => { 6582 console.info('key derivation output is ' + secret.data); 6583 }).catch((error: BusinessError) => { 6584 console.error("key derivation error, " + error.message); 6585 }); 6586 ``` 6587 6588- HKDF 6589 ```ts 6590 import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 6591 import { BusinessError } from '@kit.BasicServicesKit'; 6592 6593 let spec: cryptoFramework.HKDFSpec = { 6594 algName: 'HKDF', 6595 key: '123456', 6596 salt: new Uint8Array(16), 6597 info: new Uint8Array(16), 6598 keySize: 32 6599 }; 6600 let kdf = cryptoFramework.createKdf('HKDF|SHA256|EXTRACT_AND_EXPAND'); 6601 let kdfPromise = kdf.generateSecret(spec); 6602 kdfPromise.then(secret => { 6603 console.info('key derivation output is ' + secret.data); 6604 }).catch((error: BusinessError) => { 6605 console.error("key derivation error, " + error.message); 6606 }); 6607 ``` 6608 6609### generateSecretSync<sup>12+</sup> 6610 6611generateSecretSync(params: KdfSpec): DataBlob 6612 6613Generates a key based on the specified key derivation parameters. This API returns the result synchronously. 6614 6615**Atomic service API**: This API can be used in atomic services since API version 12. 6616 6617**System capability**: SystemCapability.Security.CryptoFramework.Kdf 6618 6619**Parameters** 6620 6621| Name| Type | Mandatory| Description | 6622| ------ | ------ | ---- | ---------------------- | 6623| params | [KdfSpec](#kdfspec11) | Yes | Parameters of the key derivation function.| 6624 6625**Return value** 6626 6627| Type | Description | 6628| ------------------ | -------- | 6629| [DataBlob](#datablob) | Key derived.| 6630 6631**Error codes** 6632For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 6633 6634| ID| Error Message | 6635| -------- | ---------------------- | 6636| 401 | invalid parameters. Possible causes: <br>1. Mandatory parameters are left unspecified;<br>2. Incorrect parameter types;<br>3. Parameter verification failed. | 6637| 17620001 | memory operation failed. | 6638| 17620002 | failed to convert parameters between arkts and c. | 6639| 17630001 | crypto operation error. | 6640 6641**Example** 6642 6643- PBKDF2 6644 ```ts 6645 import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 6646 6647 let spec: cryptoFramework.PBKDF2Spec = { 6648 algName: 'PBKDF2', 6649 password: '123456', 6650 salt: new Uint8Array(16), 6651 iterations: 10000, 6652 keySize: 32 6653 }; 6654 let kdf = cryptoFramework.createKdf('PBKDF2|SHA256'); 6655 let secret = kdf.generateSecretSync(spec); 6656 console.info("[Sync]key derivation output is " + secret.data); 6657 ``` 6658 6659- HKDF 6660 ```ts 6661 import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 6662 6663 let spec: cryptoFramework.HKDFSpec = { 6664 algName: 'HKDF', 6665 key: '123456', 6666 salt: new Uint8Array(16), 6667 info: new Uint8Array(16), 6668 keySize: 32 6669 }; 6670 let kdf = cryptoFramework.createKdf('HKDF|SHA256|EXTRACT_AND_EXPAND'); 6671 let secret = kdf.generateSecretSync(spec); 6672 console.info("[Sync]key derivation output is " + secret.data); 6673 ``` 6674 6675## SignatureUtils<sup>20+</sup> 6676 6677Provides utilities for converting SM2 data. 6678 6679### genEccSignatureSpec<sup>20+</sup> 6680 6681static genEccSignatureSpec(data: Uint8Array): EccSignatureSpec 6682 6683Generates r and s from the SM2 signature data in ASN1 DER format. 6684 6685**Atomic service API**: This API can be used in atomic services since API version 20. 6686 6687**System capability**: SystemCapability.Security.CryptoFramework.Signature 6688 6689**Parameters** 6690 6691| Name| Type | Mandatory| Description | 6692| ------ | ------ | ---- | ---------------------- | 6693| data | Uint8Array | Yes | Signature data in ASN1 DER format.| 6694 6695**Return value** 6696 6697| Type | Description | 6698| ------------------ | -------- | 6699| [EccSignatureSpec](#eccsignaturespec20) | struct that contains r and s.| 6700 6701**Error codes** 6702For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 6703 6704| ID| Error Message | 6705| -------- | ---------------------- | 6706| 17620001 | memory operation failed. | 6707| 17620002 | failed to convert parameters between arkts and c. | 6708| 17620003 | parameter check failed. Possible causes: <br>1. The length of the data parameter is 0 or too large. | 6709| 17630001 | crypto operation error. | 6710 6711**Example** 6712 6713 ```ts 6714 import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 6715 import { BusinessError } from '@kit.BasicServicesKit'; 6716 6717 function testGenEccSignatureSpec() { 6718 try { 6719 let data = 6720 new Uint8Array([48, 69, 2, 33, 0, 216, 15, 76, 238, 158, 165, 108, 76, 72, 63, 115, 52, 255, 51, 149, 54, 224, 6721 179, 49, 225, 70, 36, 117, 88, 154, 154, 27, 194, 161, 3, 1, 115, 2, 32, 51, 9, 53, 55, 248, 82, 7, 159, 179, 6722 144, 57, 151, 195, 17, 31, 106, 123, 32, 139, 219, 6, 253, 62, 240, 181, 134, 214, 107, 27, 230, 175, 40]) 6723 let spec: cryptoFramework.EccSignatureSpec = cryptoFramework.SignatureUtils.genEccSignatureSpec(data) 6724 console.info('genEccSignatureSpec success'); 6725 } catch (err) { 6726 let e: BusinessError = err as BusinessError; 6727 console.error(`ecc error, ${e.code}, ${e.message}`); 6728 } 6729 } 6730 ``` 6731 6732 6733### genEccSignature<sup>20+</sup> 6734 6735static genEccSignature(spec: EccSignatureSpec): Uint8Array; 6736 6737Converts an SM2 signature (r, s) to the ASN1 DER format. 6738 6739**Atomic service API**: This API can be used in atomic services since API version 20. 6740 6741**System capability**: SystemCapability.Security.CryptoFramework.Signature 6742 6743**Parameters** 6744 6745| Name| Type | Mandatory| Description | 6746| ------ | ------ | ---- | ---------------------- | 6747| spec | [EccSignatureSpec](#eccsignaturespec20) | Yes | SM2 signature data to convert.| 6748 6749**Return value** 6750 6751| Type | Description | 6752| ------------------ | -------- | 6753| Uint8Array | Signature data in ASN1 DER format.| 6754 6755**Error codes** 6756For details about the error codes, see [Crypto Framework Error Codes](errorcode-crypto-framework.md). 6757 6758| ID| Error Message | 6759| -------- | ---------------------- | 6760| 17620001 | memory operation failed. | 6761| 17620002 | failed to convert parameters between arkts and c. | 6762| 17620003 | parameter check failed. Possible causes: <br>1. The r or s value of the spec parameter is 0 or too large. | 6763| 17630001 | crypto operation error. | 6764 6765**Example** 6766 6767 ```ts 6768 import { cryptoFramework } from '@kit.CryptoArchitectureKit'; 6769 import { BusinessError } from '@kit.BasicServicesKit'; 6770 6771 function testGenEccSignature() { 6772 try { 6773 let spec: cryptoFramework.EccSignatureSpec = { 6774 r: BigInt('97726608965854271693043443511967021777934035174185659091642456228829830775155'), 6775 s: BigInt('23084224202834231287427338597254751764391338275617140205467537273296855150376'), 6776 } 6777 6778 let data = cryptoFramework.SignatureUtils.genEccSignature(spec) 6779 console.info('genEccSignature success'); 6780 console.info('data is ' + data) 6781 } catch (err) { 6782 let e: BusinessError = err as BusinessError; 6783 console.error(`ecc error, ${e.code}, ${e.message}`); 6784 } 6785 } 6786 ``` 6787