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