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