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. 8 9## Modules to Import 10 11```javascript 12import cryptoFramework from "@ohos.security.cryptoFramework" 13``` 14 15## Result 16 17Enumerates the error codes. 18 19**System capability**: SystemCapability.Security.CryptoFramework 20 21| Name | Value | Description | 22| ------------------------------------- | -------- | ---------------------------- | 23| INVALID_PARAMS | 401 | Invalid parameters. | 24| NOT_SUPPORT | 801 | Unsupported operation. | 25| ERR_OUT_OF_MEMORY | 17620001 | Memory error. | 26| ERR_RUNTIME_ERROR | 17620002 | Runtime error. | 27| ERR_CRYPTO_OPERATION | 17630001 | Cryptographic operation error. | 28 29## DataBlob 30 31Defines a binary data array. 32 33**System capability**: SystemCapability.Security.CryptoFramework 34 35| Name| Type | Readable| Writable| Description | 36| ---- | ---------- | ---- | ---- | ------ | 37| data | Uint8Array | Yes | Yes | Binary data array. | 38 39 40## cryptoFramework.createMac 41 42createMac(algName : string) : Mac 43 44Creates a **Mac** instance for message authentication code (MAC) operations. 45 46For details about the supported specifications, see [HMAC Algorithm Specifications](../../security/cryptoFramework-overview.md#hmac-algorithm-specifications). 47 48**System capability**: SystemCapability.Security.CryptoFramework 49 50**Parameters** 51 52| Name | Type | Mandatory| Description | 53| ------- | ------ | ---- | ------------------------------------------------------------ | 54| algName | string | Yes | Digest algorithm. For details about the supported algorithms, see [HMAC Algorithm Specifications](../../security/cryptoFramework-overview.md#hmac-algorithm-specifications).| 55 56**Return value** 57 58| Type| Description | 59| ---- | --------------------------------------- | 60| Mac | [Mac](#mac) instance created.| 61 62**Error codes** 63 64| ID| Error Message | 65| -------- | ------------------ | 66| 17620001 | memory error. | 67 68**Example** 69 70```javascript 71import cryptoFramework from "@ohos.security.cryptoFramework" 72 73var mac; 74try { 75 // Set algName based on the algorithm supported. 76 mac = cryptoFramework.createMac("SHA256"); 77} catch (error) { 78 console.error("[Promise]: error code: " + error.code + ", message is: " + error.message); 79} 80``` 81 82## Mac 83 84Provides APIs for MAC operations. Before using any API of the **Mac** class, you must create a **Mac** instance by using [createMac](#cryptoframeworkcreatemac). 85 86### Attributes 87 88**System capability**: SystemCapability.Security.CryptoFramework 89 90| Name | Type | Readable| Writable| Description | 91| ------- | ------ | ---- | ---- | -------------------- | 92| algName | string | Yes | No | Digest algorithm to use.| 93 94### init 95 96init(key : SymKey, callback : AsyncCallback\<void>) : void; 97 98Initializes the MAC computation using a symmetric key. This API uses an asynchronous callback to return the result. 99 100**System capability**: SystemCapability.Security.CryptoFramework 101 102**Parameters** 103 104| Name | Type | Mandatory| Description | 105| -------- | -------------------- | ---- | ------------ | 106| key | [SymKey](#symkey) | Yes | Shared symmetric key.| 107| callback | AsyncCallback\<void> | Yes | Callback invoked to return the result. | 108 109**Error codes** 110 111| ID| Error Message | 112| -------- | ---------------------- | 113| 17630001 | crypto operation error. | 114 115**Example** 116 117```javascript 118import cryptoFramework from "@ohos.security.cryptoFramework" 119 120var mac; 121try { 122 mac = cryptoFramework.createMac("SHA256"); 123} catch (error) { 124 console.error("[Promise]: error code: " + error.code + ", message is: " + error.message); 125} 126var KeyBlob; 127var symKeyGenerator = cryptoFramework.createSymKeyGenerator("AES128"); 128symKeyGenerator.convertKey(KeyBlob, (err, symKey) => { 129 if (err) { 130 console.error("[Callback] err: " + err.code); 131 } 132 mac.init(symKey, (err1, ) => { 133 if (err1) { 134 console.error("[Callback] err: " + err1.code); 135 } 136 }); 137}); 138``` 139 140### init 141 142init(key : SymKey) : Promise\<void>; 143 144Initializes the MAC computation using a symmetric key. This API uses a promise to return the result. 145 146**System capability**: SystemCapability.Security.CryptoFramework 147 148**Parameters** 149 150| Name| Type | Mandatory| Description | 151| ------ | ------ | ---- | ------------ | 152| key | [SymKey](#symkey) | Yes | Shared symmetric key.| 153 154**Return value** 155 156| Type | Description | 157| -------------- | ----------- | 158| Promise\<void> | Promise used to return the result.| 159 160**Error codes** 161 162| ID| Error Message | 163| -------- | ---------------------- | 164| 17630001 | crypto operation error. | 165 166**Example** 167 168```javascript 169import cryptoFramework from "@ohos.security.cryptoFramework" 170 171var mac; 172try { 173 mac = cryptoFramework.createMac("SHA256"); 174} catch (error) { 175 console.error("[Promise]: error code: " + error.code + ", message is: " + error.message); 176} 177console.error("Mac algName is: " + mac.algName); 178 179var KeyBlob; 180var symKeyGenerator = cryptoFramework.createSymKeyGenerator("AES128"); 181var promiseConvertKey = symKeyGenerator.convertKey(KeyBlob); 182promiseConvertKey.then(symKey => { 183 var promiseMacInit = mac.init(symKey); 184 return promiseMacInit; 185}).catch(error => { 186 console.error("[Promise]: error: " + error.message); 187}); 188 189``` 190 191### update 192 193update(input : DataBlob, callback : AsyncCallback\<void>) : void; 194 195Updates the MAC computation data. This API uses an asynchronous callback to return the result. 196 197> **NOTE**<br> 198> For details about the sample code for calling **update()** multiple times, see [Generating a MAC](../../security/cryptoFramework-guidelines.md#generating-a-mac). 199 200**System capability**: SystemCapability.Security.CryptoFramework 201 202**Parameters** 203 204| Name | Type | Mandatory| Description | 205| -------- | -------------------- | ---- | ---------- | 206| input | [DataBlob](#datablob)| Yes | Data to pass in.| 207| callback | AsyncCallback\<void> | Yes | Callback invoked to return the result. | 208 209**Error codes** 210 211| ID| Error Message | 212| -------- | ---------------------- | 213| 17630001 | crypto operation error. | 214 215**Example** 216 217```javascript 218import cryptoFramework from "@ohos.security.cryptoFramework" 219 220var KeyBlob; 221var mac; 222try { 223 mac = cryptoFramework.createMac("SHA256"); 224} catch (error) { 225 console.error("[Callback]: error code: " + error.code + ", message is: " + error.message); 226} 227var symKeyGenerator = cryptoFramework.createSymKeyGenerator("AES128"); 228symKeyGenerator.convertKey(KeyBlob, (err, symKey) => { 229 if (err) { 230 console.error("[Callback] err: " + err.code); 231 } 232 mac.init(symKey, (err1, ) => { 233 if (err1) { 234 console.error("[Callback] err: " + err1.code); 235 } 236 let blob; 237 mac.update(blob, (err2, data) => { 238 if (err2) { 239 console.error("[Callback] err: " + err2.code); 240 } 241 }); 242 }); 243}); 244``` 245 246### update 247 248update(input : DataBlob) : Promise\<void>; 249 250Updates the MAC computation data. This API uses a promise to return the result. 251 252> **NOTE**<br> 253> For details about the sample code for calling **update()** multiple times, see [Generating a MAC](../../security/cryptoFramework-guidelines.md#generating-a-mac). 254 255**System capability**: SystemCapability.Security.CryptoFramework 256 257**Parameters** 258 259| Name| Type | Mandatory| Description | 260| ------ | -------- | ---- | ---------- | 261| input | [DataBlob](#datablob) | Yes | Data to pass in.| 262 263**Return value** 264 265| Type | Description | 266| -------------- | ----------- | 267| Promise\<void> | Promise used to return the result.| 268 269**Error codes** 270 271| ID| Error Message | 272| -------- | ---------------------- | 273| 17630001 | crypto operation error. | 274 275**Example** 276 277```javascript 278import cryptoFramework from "@ohos.security.cryptoFramework" 279 280var mac; 281try { 282 mac = cryptoFramework.createMac("SHA256"); 283} catch (error) { 284 console.error("[Promise]: error code: " + error.code + ", message is: " + error.message); 285} 286console.error("Mac algName is: " + mac.algName); 287 288var KeyBlob; 289var symKeyGenerator = cryptoFramework.createSymKeyGenerator("AES128"); 290var promiseConvertKey = symKeyGenerator.convertKey(KeyBlob); 291promiseConvertKey.then(symKey => { 292 var promiseMacInit = mac.init(symKey); 293 return promiseMacInit; 294}).then(() => { 295 let blob; 296 var promiseMacUpdate = mac.update(blob); 297 return promiseMacUpdate; 298}).catch(error => { 299 console.error("[Promise]: error: " + error.message); 300}); 301 302``` 303 304### doFinal 305 306doFinal(callback : AsyncCallback\<DataBlob>) : void; 307 308Finalizes the MAC computation. This API uses an asynchronous callback to return the result. 309 310**System capability**: SystemCapability.Security.CryptoFramework 311 312**Parameters** 313 314| Name | Type | Mandatory| Description | 315| -------- | ------------------------ | ---- | -------- | 316| callback | AsyncCallback\<[DataBlob](#datablob)> | Yes | Callback invoked to return the result.| 317 318**Error codes** 319 320| ID| Error Message | 321| -------- | ---------------------- | 322| 17620001 | memory error. | 323| 17630001 | crypto operation error. | 324 325**Example** 326 327```javascript 328import cryptoFramework from "@ohos.security.cryptoFramework" 329 330var KeyBlob; 331var mac; 332try { 333 mac = cryptoFramework.createMac("SHA256"); 334} catch (error) { 335 console.error("[Callback]: error code: " + error.code + ", message is: " + error.message); 336} 337var symKeyGenerator = cryptoFramework.createSymKeyGenerator("AES128"); 338symKeyGenerator.convertKey(KeyBlob, (err, symKey) => { 339 if (err) { 340 console.error("[Callback] err: " + err.code); 341 } 342 mac.init(symKey, (err1, ) => { 343 if (err1) { 344 console.error("[Callback] err: " + err1.code); 345 } 346 let blob; 347 mac.update(blob, (err2, ) => { 348 if (err2) { 349 console.error("[Callback] err: " + err2.code); 350 } 351 mac.doFinal((err3, macOutput) => { 352 if (err3) { 353 console.error("[Callback] err: " + err3.code); 354 } else { 355 console.error("[Promise]: HMAC result: " + macOutput); 356 } 357 }); 358 }); 359 }); 360}); 361``` 362 363### doFinal 364 365doFinal() : Promise\<DataBlob> 366 367Finalizes the MAC computation. This API uses a promise to return the result. 368 369**System capability**: SystemCapability.Security.CryptoFramework 370 371**Return value** 372 373| Type | Description | 374| ------------------ | ----------- | 375| Promise\<[DataBlob](#datablob)> | Promise used to return the result.| 376 377**Error codes** 378 379| ID| Error Message | 380| -------- | ---------------------- | 381| 17620001 | memory error. | 382| 17630001 | crypto operation error. | 383 384**Example** 385 386```javascript 387import cryptoFramework from "@ohos.security.cryptoFramework" 388 389var mac; 390try { 391 mac = cryptoFramework.createMac("SHA256"); 392} catch (error) { 393 console.error("[Promise]: error code: " + error.code + ", message is: " + error.message); 394} 395console.error("Mac algName is: " + mac.algName); 396 397var KeyBlob; 398var symKeyGenerator = cryptoFramework.createSymKeyGenerator("AES128"); 399var promiseConvertKey = symKeyGenerator.convertKey(KeyBlob); 400promiseConvertKey.then(symKey => { 401 var promiseMacInit = mac.init(symKey); 402 return promiseMacInit; 403}).then(() => { 404 let blob; 405 var promiseMacUpdate = mac.update(blob); 406 return promiseMacUpdate; 407}).then(() => { 408 var PromiseMacDoFinal = mac.doFinal(); 409 return PromiseMacDoFinal; 410}).then(macOutput => { 411 console.error("[Promise]: HMAC result: " + macOutput.data); 412}).catch(error => { 413 console.error("[Promise]: error: " + error.message); 414}); 415``` 416 417### getMacLength 418 419getMacLength() : number 420 421Obtains the MAC length, in bytes. 422 423**System capability**: SystemCapability.Security.CryptoFramework 424 425**Return value** 426 427| Type | Description | 428| ------ | ------------------------- | 429| number | MAC length obtained.| 430 431**Error codes** 432 433| ID| Error Message | 434| -------- | ---------------------- | 435| 17630001 | crypto operation error. | 436 437**Example** 438 439```javascript 440import cryptoFramework from "@ohos.security.cryptoFramework" 441 442var mac; 443try { 444 mac = cryptoFramework.createMac("SHA256"); 445} catch (error) { 446 console.error("[Promise]: error code: " + error.code + ", message is: " + error.message); 447} 448console.error("Mac algName is: " + mac.algName); 449 450var KeyBlob; 451var symKeyGenerator = cryptoFramework.createSymKeyGenerator("AES128"); 452var promiseConvertKey = symKeyGenerator.convertKey(KeyBlob); 453promiseConvertKey.then(symKey => { 454 var promiseMacInit = mac.init(symKey); 455 return promiseMacInit; 456}).then(() => { 457 let blob; 458 var promiseMacUpdate = mac.update(blob); 459 return promiseMacUpdate; 460}).then(() => { 461 var PromiseMacDoFinal = mac.doFinal(); 462 return PromiseMacDoFinal; 463}).then(macOutput => { 464 console.error("[Promise]: HMAC result: " + macOutput.data); 465 let macLen = mac.getMacLength(); 466 console.error("MAC len: " + macLen); 467}).catch(error => { 468 console.error("[Promise]: error: " + error.message); 469}); 470``` 471 472## cryptoFramework.createMd 473 474createMd(algName : string) : Md 475 476Creates an **Md** instance for message digest operations. 477 478For details about the supported specifications, see [MD Algorithm Specifications](../../security/cryptoFramework-overview.md#md-algorithm-specifications). 479 480**System capability**: SystemCapability.Security.CryptoFramework 481 482**Parameters** 483 484| Name | Type | Mandatory| Description | 485| ------- | ------ | ---- | ------------------------------------------------------------ | 486| algName | string | Yes | Digest algorithm. For details about the supported algorithms, see [MD Algorithm Specifications](../../security/cryptoFramework-overview.md#md-algorithm-specifications).| 487 488**Return value** 489 490| Type| Description | 491| ---- | ------------------------------------- | 492| Md | [Md](#md) instance created.| 493 494**Error codes** 495 496| ID| Error Message | 497| -------- | ------------------ | 498| 17620001 | memory error. | 499 500**Example** 501 502```javascript 503import cryptoFramework from "@ohos.security.cryptoFramework" 504 505var md; 506try { 507 // Set algName based on the algorithm supported. 508 md = cryptoFramework.createMd("SHA256"); 509} catch (error) { 510 console.error("[Promise]: error code: " + error.code + ", message is: " + error.message); 511} 512``` 513 514## Md 515 516Provides APIs for message digest operations. Before using any API of the **Md** class, you must create an **Md** instance by using [createMd](#cryptoframeworkcreatemd). 517 518### Attributes 519 520**System capability**: SystemCapability.Security.CryptoFramework 521 522| Name | Type | Readable| Writable| Description | 523| ------- | ------ | ---- | ---- | -------------------- | 524| algName | string | Yes | No | Digest algorithm.| 525 526### update 527 528update(input : DataBlob, callback : AsyncCallback\<void>) : void; 529 530Updates the message digest data. This API uses an asynchronous callback to return the result. 531 532> **NOTE**<br> 533> For details about the sample code for calling **update()** multiple times, see [Generating a Digest](../../security/cryptoFramework-guidelines.md#generating-a-digest). 534 535**System capability**: SystemCapability.Security.CryptoFramework 536 537**Parameters** 538 539| Name | Type | Mandatory| Description | 540| -------- | -------------------- | ---- | ---------- | 541| input | [DataBlob](#datablob)| Yes | Data to pass in.| 542| callback | AsyncCallback\<void> | Yes | Callback invoked to return the result. | 543 544**Error codes** 545 546| ID| Error Message | 547| -------- | ---------------------- | 548| 17630001 | crypto operation error. | 549 550**Example** 551 552```javascript 553import cryptoFramework from "@ohos.security.cryptoFramework" 554 555var md; 556try { 557 md = cryptoFramework.createMd("SHA256"); 558} catch (error) { 559 console.error("[Callback]: error code: " + error.code + ", message is: " + error.message); 560} 561console.error("Md algName is: " + md.algName); 562 563let blob; 564md.update(blob, (err,) => { 565 if (err) { 566 console.error("[Callback] err: " + err.code); 567 } 568}); 569``` 570 571### update 572 573update(input : DataBlob) : Promise\<void>; 574 575Updates the message digest data. This API uses a promise to return the result. 576 577> **NOTE**<br> 578> For details about the sample code for calling **update()** multiple times, see [Generating a Digest](../../security/cryptoFramework-guidelines.md#generating-a-digest). 579 580**System capability**: SystemCapability.Security.CryptoFramework 581 582| Name| Type | Mandatory| Description | 583| ------ | -------- | ---- | ---------- | 584| input | DataBlob | Yes | Data to pass in.| 585 586**Return value** 587 588| Type | Description | 589| -------------- | ----------- | 590| Promise\<void> | Promise used to return the result.| 591 592**Error codes** 593 594| ID| Error Message | 595| -------- | ---------------------- | 596| 17630001 | crypto operation error. | 597 598**Example** 599 600```javascript 601import cryptoFramework from "@ohos.security.cryptoFramework" 602 603var md; 604try { 605 md = cryptoFramework.createMd("SHA256"); 606} catch (error) { 607 console.error("[Callback]: error code: " + error.code + ", message is: " + error.message); 608} 609console.error("Md algName is: " + md.algName); 610 611let blob; 612var promiseMdUpdate = md.update(blob); 613promiseMdUpdate.then(() => { 614 // do something 615}).catch(error => { 616 console.error("[Promise]: error: " + error.message); 617}); 618``` 619 620### digest 621 622digest(callback : AsyncCallback\<DataBlob>) : void 623 624Generates a message digest. This API uses an asynchronous callback to return the result. 625 626**System capability**: SystemCapability.Security.CryptoFramework 627 628| Name | Type | Mandatory| Description | 629| -------- | ------------------------ | ---- | -------- | 630| callback | AsyncCallback\<DataBlob> | Yes | Callback invoked to return the result.| 631 632**Error codes** 633 634| ID| Error Message | 635| -------- | ---------------------- | 636| 17620001 | memory error. | 637| 17630001 | crypto operation error. | 638 639**Example** 640 641```javascript 642import cryptoFramework from "@ohos.security.cryptoFramework" 643 644var md; 645try { 646 md = cryptoFramework.createMd("SHA256"); 647} catch (error) { 648 console.error("[Callback]: error code: " + error.code + ", message is: " + error.message); 649} 650console.error("Md algName is: " + md.algName); 651 652let blob; 653md.update(blob, (err,) => { 654 if (err) { 655 console.error("[Callback] err: " + err.code); 656 } 657 md.digest((err1, mdOutput) => { 658 if (err1) { 659 console.error("[Callback] err: " + err1.code); 660 } else { 661 console.error("[Callback]: MD result: " + mdOutput); 662 } 663 }); 664}); 665``` 666 667### digest 668 669digest() : Promise\<DataBlob> 670 671Generates a message digest. This API uses a promise to return the result. 672 673**System capability**: SystemCapability.Security.CryptoFramework 674 675**Return value** 676 677| Type | Description | 678| ------------------ | ----------- | 679| Promise\<[DataBlob](#datablob)> | Promise used to return the result.| 680 681**Error codes** 682 683| ID| Error Message | 684| -------- | ---------------------- | 685| 17620001 | memory error. | 686| 17630001 | crypto operation error. | 687 688**Example** 689 690```javascript 691import cryptoFramework from "@ohos.security.cryptoFramework" 692 693var md; 694try { 695 md = cryptoFramework.createMd("SHA256"); 696} catch (error) { 697 console.error("[Callback]: error code: " + error.code + ", message is: " + error.message); 698} 699console.error("Md algName is: " + md.algName); 700 701let blob; 702var promiseMdUpdate = md.update(blob); 703promiseMdUpdate.then(() => { 704 var PromiseMdDigest = md.digest(); 705 return PromiseMdDigest; 706}).then(mdOutput => { 707 console.error("[Promise]: MD result: " + mdOutput.data); 708}).catch(error => { 709 console.error("[Promise]: error: " + error.message); 710}); 711``` 712 713### getMdLength 714 715getMdLength() : number 716 717Obtains the message digest length, in bytes. 718 719**System capability**: SystemCapability.Security.CryptoFramework 720 721**Return value** 722 723| Type | Description | 724| ------ | ------------------------ | 725| number | Message digest length obtained.| 726 727**Error codes** 728 729| ID| Error Message | 730| -------- | ---------------------- | 731| 17630001 | crypto operation error. | 732 733**Example** 734 735```javascript 736import cryptoFramework from "@ohos.security.cryptoFramework" 737 738var md; 739try { 740 md = cryptoFramework.createMd("SHA256"); 741} catch (error) { 742 console.error("[Callback]: error code: " + error.code + ", message is: " + error.message); 743} 744console.error("Md algName is: " + md.algName); 745 746let blob; 747var promiseMdUpdate = md.update(blob); 748promiseMdUpdate.then(() => { 749 var PromiseMdDigest = md.digest(); 750 return PromiseMdDigest; 751}).then(mdOutput => { 752 console.error("[Promise]: MD result: " + mdOutput.data); 753 let mdLen = md.getMdLength(); 754 console.error("MD len: " + mdLen); 755}).catch(error => { 756 console.error("[Promise]: error: " + error.message); 757}); 758``` 759 760## cryptoFramework.createRandom 761 762createRandom() : Random 763 764Creates a **Random** instance for generating a random number and setting a seed. 765 766**System capability**: SystemCapability.Security.CryptoFramework 767 768**Return value** 769 770| Type | Description | 771| ------ | --------------------------------------------- | 772| Random | [Random](#random) instance created.| 773 774**Error codes** 775 776| ID| Error Message | 777| -------- | ------------ | 778| 17620001 | memory error. | 779 780**Example** 781 782```javascript 783import cryptoFramework from "@ohos.security.cryptoFramework" 784 785try { 786 var rand = cryptoFramework.createRandom(); 787} catch (error) { 788 console.error("[Callback]: error code: " + error.code + ", message is: " + error.message); 789} 790``` 791 792## Random 793 794Provides 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). 795 796### generateRandom 797 798generateRandom(len : number, callback: AsyncCallback\<DataBlob>) : void; 799 800Generates a random number of the given length. This API uses an asynchronous callback to return the result. 801 802**System capability**: SystemCapability.Security.CryptoFramework 803 804**Parameters** 805 806| Name | Type | Mandatory| Description | 807| -------- | ------------------------ | ---- | -------------------- | 808| len | number | Yes | Length of the random number to generate.| 809| callback | AsyncCallback\<[DataBlob](#datablob)> | Yes | Callback invoked to return the result. | 810 811**Error codes** 812 813| ID| Error Message | 814| -------- | ---------------------- | 815| 17620001 | memory error. | 816| 17630001 | crypto operation error. | 817 818**Example** 819 820```javascript 821import cryptoFramework from "@ohos.security.cryptoFramework" 822 823var rand; 824try { 825 rand = cryptoFramework.createRandom(); 826} catch (error) { 827 console.error("[Callback]: error code: " + error.code + ", message is: " + error.message); 828} 829rand.generateRandom(12, (err, randData) => { 830 if (err) { 831 console.error("[Callback] err: " + err.code); 832 } else { 833 console.error("[Callback]: generate random result: " + randData.data); 834 } 835}); 836``` 837 838### generateRandom 839 840generateRandom(len : number) : Promise\<DataBlob>; 841 842Generates a random number of the given length. This API uses a promise to return the result. 843 844**System capability**: SystemCapability.Security.CryptoFramework 845 846**Parameters** 847 848| Name| Type | Mandatory| Description | 849| ------ | ------ | ---- | -------------------- | 850| len | number | Yes | Length of the random number to generate.| 851 852**Return value** 853 854| Type | Description | 855| ------------------ | ----------- | 856| Promise\<[DataBlob](#datablob)> | Promise used to return the result.| 857 858**Error codes** 859 860| ID| Error Message | 861| -------- | ---------------------- | 862| 17620001 | memory error. | 863| 17630001 | crypto operation error. | 864 865**Example** 866 867```javascript 868import cryptoFramework from "@ohos.security.cryptoFramework" 869 870var rand; 871try { 872 rand = cryptoFramework.createRandom(); 873} catch (error) { 874 console.error("[Callback]: error code: " + error.code + ", message is: " + error.message); 875} 876 877var promiseGenerateRand = rand.generateRandom(12); 878promiseGenerateRand.then(randData => { 879 console.error("[Promise]: rand result: " + randData.data); 880}).catch(error => { 881 console.error("[Promise]: error: " + error.message); 882}); 883``` 884 885### setSeed 886 887setSeed(seed : DataBlob) : void; 888 889Sets a seed. This API uses an asynchronous callback to return the result. 890 891**System capability**: SystemCapability.Security.CryptoFramework 892 893| Name | Type | Mandatory| Description | 894| -------- | --------------------- | ---- | ---------- | 895| seed | DataBlob | Yes | Seed to set.| 896 897**Error codes** 898 899| ID| Error Message | 900| -------- | ----------------- | 901| 17620001 | memory error. | 902 903**Example** 904 905```javascript 906import cryptoFramework from "@ohos.security.cryptoFramework" 907 908var rand; 909try { 910 rand = cryptoFramework.createRandom(); 911} catch (error) { 912 console.error("[Callback]: error code: " + error.code + ", message is: " + error.message); 913} 914 915rand.generateRandom(12, (err, randData) => { 916 if (err) { 917 console.error("[Callback] err: " + err.code); 918 } else { 919 console.error("[Callback]: generate random result: " + randData.data); 920 try { 921 rand.setSeed(randData); 922 } catch (error) { 923 console.log("setSeed failed, errCode: " + error.code + ", errMsg: " + error.message); 924 } 925 } 926}); 927``` 928 929## ParamsSpec 930 931Defines the parameters used for encryption and decryption. 932 933For the symmetric encryption and decryption modes that require parameters such as the initialization vector (IV), you must construct a child class object and pass it to [init()](#init-2). If no IV is required (for example, the ECB mode is used), pass in **null** in [init()](#init-2). 934 935**System capability**: SystemCapability.Security.CryptoFramework 936 937| Name | Type | Readable| Writable| Description | 938| ------- | ------ | ---- | ---- | ------------------------------------------------------------ | 939| algName | string | Yes | Yes | Symmetric encryption and decryption parameters. Options:<br>- **IvParamsSpec**: applicable to the CBC, CTR, OFB, and CFB modes.<br>- **GcmParamsSpec**: applicable to the GCM mode.<br>- **CcmParamsSpec**: applicable to the CCM mode.| 940 941> **NOTE**<br> 942> The **params** parameter in [init()](#init-2) is of the **ParamsSpec** type (parent class), but a child class object (such as **IvParamsSpec**) needs to be passed in. When constructing the child class object, set **algName** in the parent class **ParamsSpec** to let the algorithm library know the type of child class object to pass in in **init()**. 943 944## IvParamsSpec 945 946Defines the child class of [ParamsSpec](#paramsspec). It is used as the parameters of [init()](#init-2) during symmetric encryption and decryption. 947 948**IvParamsSpec** applies to the encryption and decryption modes such as CBC, CTR, OFB, and CFB, which use only the IV. 949 950**System capability**: SystemCapability.Security.CryptoFramework 951 952| Name| Type | Readable| Writable| Description | 953| ---- | --------------------- | ---- | ---- | ------------------------------------------------------------ | 954| iv | [DataBlob](#datablob) | Yes | Yes | IV for encryption and decryption. Options:<br>- AES CBC, CTR, OFB, or CFB mode: 16-byte IV<br>- 3DES CBC, OFB, or CFB mode: 8-byte IV| 955 956> **NOTE**<br> 957> Before passing **IvParamsSpec** to [init()](#init-2), specify **algName** in its parent class [ParamsSpec](#paramsspec). 958 959## GcmParamsSpec 960 961Defines the child class of [ParamsSpec](#paramsspec) for the GCM mode. It is used as the parameters of [init()](#init-2) during symmetric encryption and decryption. 962 963**GcmParamsSpec** applies to the GCM mode. 964 965**System capability**: SystemCapability.Security.CryptoFramework 966 967| Name | Type | Readable| Writable| Description | 968| ------- | --------------------- | ---- | ---- | ------------------------------------------------------------ | 969| iv | [DataBlob](#datablob) | Yes | Yes | IV, which is of 12 bytes. | 970| aad | [DataBlob](#datablob) | Yes | Yes | Additional authenticated data (AAD), which is of 8 bytes. | 971| authTag | [DataBlob](#datablob) | Yes | Yes | Authentication tag, which is of 16 bytes.<br>When the GCM mode is used for encryption, [DataBlob](#datablob) output by [doFinal()](#dofinal-2) is required. The last 16 bytes of [DataBlob](#datablob) are used as as **authTag** in [GcmParamsSpec](#gcmparamsspec) of [init()](#init-2). | 972 973> **NOTE** 974> Before passing **GcmParamsSpec** to [init()](#init-2), specify **algName** in its parent class [ParamsSpec](#paramsspec). 975 976## CcmParamsSpec 977 978Defines the child class of [ParamsSpec](#paramsspec) for the CCM mode. It is used as the parameters of [init()](#init-2) during symmetric encryption and decryption. 979 980**CcmParamsSpec** applies to the CCM mode. 981 982**System capability**: SystemCapability.Security.CryptoFramework 983 984| Name | Type | Readable| Writable| Description | 985| ------- | --------------------- | ---- | ---- | ------------------------------------------------------------ | 986| iv | [DataBlob](#datablob) | Yes | Yes | IV, which is of 7 bytes. | 987| aad | [DataBlob](#datablob) | Yes | Yes | AAD, which is of 8 bytes. | 988| authTag | [DataBlob](#datablob) | Yes | Yes | Authentication tag, which is of 12 bytes.<br>When the CCM mode is used for encryption, [DataBlob](#datablob) output by [doFinal()](#dofinal-2) is required. The last 12 bytes of [DataBlob](#datablob) are used as as **authTag** in [CcmParamsSpec](#ccmparamsspec) of [init()](#init-2).| 989 990> **NOTE** 991> Before passing **CcmParamsSpec** to [init()](#init-2), specify **algName** in its parent class [ParamsSpec](#paramsspec). 992 993## CryptoMode 994 995Enumerates the cryptographic operations. 996 997**System capability**: SystemCapability.Security.CryptoFramework 998 999| Name | Value | Description | 1000| ------------ | ---- | ---------------- | 1001| ENCRYPT_MODE | 0 | Encryption.| 1002| DECRYPT_MODE | 1 | Decryption.| 1003 1004## Key 1005 1006Provides APIs for key operations. Before performing cryptographic operations (such as encryption and decryption), you need to construct a child class object of **Key** and pass it to [init()](#init-2) of the [Cipher](#cipher) instance. <br>Keys can be generated by a key generator. 1007 1008### Attributes 1009 1010**System capability**: SystemCapability.Security.CryptoFramework 1011 1012| Name | Type | Readable| Writable| Description | 1013| ------- | ------ | ---- | ---- | ---------------------------- | 1014| format | string | Yes | No | Format of the key. | 1015| algName | string | Yes | No | Algorithm name (including the key length).| 1016 1017### getEncoded 1018 1019getEncoded() : DataBlob 1020 1021Obtains a key in hexadecimal format. This API returns the result synchronously. 1022 1023**System capability**: SystemCapability.Security.CryptoFramework 1024 1025**Return value** 1026 1027| Type | Description | 1028| --------------------- | ------------------------ | 1029| [DataBlob](#datablob) | Key obtained.| 1030 1031**Example** 1032 1033```js 1034import cryptoFramework from "@ohos.security.cryptoFramework" 1035function uint8ArrayToShowStr(uint8Array) { 1036 return Array.prototype.map 1037 .call(uint8Array, (x) => ('00' + x.toString(16)).slice(-2)) 1038 .join(''); 1039} 1040 1041let key; // The key is generated by a symKeyGenerator. The generation process is omitted here. 1042let encodedKey = key.getEncoded(); 1043console.info("key hex:" + uint8ArrayToShowStr(encodedKey.data)); 1044``` 1045 1046## SymKey 1047 1048Provides APIs for symmetric key operations. **SymKey** is a child class of [Key](#key), and its objects need to be passed to [init()](#init-2) of the [Cipher](#cipher) instance in symmetric encryption and decryption. 1049 1050Symmetric keys can be generated by a [SymKeyGenerator](#symkeygenerator). 1051 1052### clearMem 1053 1054clearMem() : void 1055 1056Clears 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. 1057 1058**System capability**: SystemCapability.Security.CryptoFramework 1059 1060**Example** 1061 1062```js 1063import cryptoFramework from "@ohos.security.cryptoFramework" 1064function uint8ArrayToShowStr(uint8Array) { 1065 return Array.prototype.map 1066 .call(uint8Array, (x) => ('00' + x.toString(16)).slice(-2)) 1067 .join(''); 1068} 1069 1070let key; // The key is generated by a symKeyGenerator. The generation process is omitted here. 1071let encodedKey = key.getEncoded(); 1072console.info("key hex: "+ uint8ArrayToShowStr(encodedKey.data)); // Key content is displayed. 1073key.clearMem(); 1074encodedKey = key.getEncoded(); 1075console.info("key hex:" + uint8ArrayToShowStr(encodedKey.data)); // All 0s are displayed. 1076``` 1077 1078## PubKey 1079 1080Provides APIs for public key operations. **PubKey** is a child class of [Key](#key), and its objects need to be passed in during asymmetric encryption and decryption, signature verification, and key agreement. 1081 1082Public keys can be generated by an **AsyKeyGenerator**. 1083 1084### Attributes 1085 1086**System capability**: SystemCapability.Security.CryptoFramework 1087 1088| Name | Type | Readable| Writable| Description | 1089| ------- | ------ | ---- | ---- | ---------------------------- | 1090| format | string | Yes | No | Format of the key. | 1091| algName | string | Yes | No | Algorithm name (including the key length).| 1092 1093 1094### getEncoded 1095 1096getEncoded() : DataBlob 1097 1098Obtains a key in binary format. This API returns the result synchronously. The public key format must comply with the ASN.1 syntax, X.509 specifications, and DER encoding format. 1099 1100**System capability**: SystemCapability.Security.CryptoFramework 1101 1102**Return value** 1103 1104| Type | Description | 1105| --------------------- | ------------------------ | 1106| [DataBlob](#datablob) | Key obtained.| 1107 1108**Example** 1109 1110```js 1111function uint8ArrayToShowStr(uint8Array) { 1112 return Array.prototype.map 1113 .call(uint8Array, (x) => ('00' + x.toString(16)).slice(-2)) 1114 .join(''); 1115} 1116 1117let key; // The key is a public key generated by the asymmetric key generator. The generation process is omitted here. 1118console.info("key format:" + key.format); 1119console.info("key algName:" + key.algName); 1120var encodedKey = key.getEncoded(); 1121console.info("key encoded:" + uint8ArrayToShowStr(encodedKey.data)); 1122``` 1123 1124## PriKey 1125 1126Provides APIs for private key operations. **PriKey** is a child class of [Key](#key), and its objects need to be passed in during asymmetric encryption and decryption, signature verification, and key agreement. 1127 1128Private keys can be generated by an **AsyKeyGenerator**. 1129 1130### Attributes 1131 1132**System capability**: SystemCapability.Security.CryptoFramework 1133 1134| Name | Type | Readable| Writable| Description | 1135| ------- | ------ | ---- | ---- | ---------------------------- | 1136| format | string | Yes | No | Format of the key. | 1137| algName | string | Yes | No | Algorithm name (including the key length).| 1138 1139### getEncoded 1140 1141getEncoded() : DataBlob 1142 1143Obtains a key in binary format. This API returns the result synchronously. The private key format must comply with the ASN.1 syntax, PKCS #8 specifications, and DER encoding mode. 1144 1145**System capability**: SystemCapability.Security.CryptoFramework 1146 1147**Return value** 1148 1149| Type | Description | 1150| --------------------- | ------------------------ | 1151| [DataBlob](#datablob) | Key obtained.| 1152 1153**Example** 1154 1155```js 1156function uint8ArrayToShowStr(uint8Array) { 1157 return Array.prototype.map 1158 .call(uint8Array, (x) => ('00' + x.toString(16)).slice(-2)) 1159 .join(''); 1160} 1161 1162let key; // The key is a private key generated by the asymmetric key generator. The generation process is omitted here. 1163console.info("key format:" + key.format); 1164console.info("key algName:" + key.algName); 1165var encodedKey = key.getEncoded(); 1166console.info("key encoded:" + uint8ArrayToShowStr(encodedKey.data)); 1167``` 1168 1169### clearMem 1170 1171clearMem() : void 1172 1173Clears the keys in the memory. This API returns the result synchronously. 1174 1175**System capability**: SystemCapability.Security.CryptoFramework 1176 1177**Example** 1178 1179```js 1180let key; // The key is a private key generated by the asymmetric key generator. The generation process is omitted here. 1181key.clearMem(); 1182``` 1183 1184## KeyPair 1185 1186Defines an asymmetric key pair, which includes a public key and a private key. 1187 1188Asymmetric key pairs can be generated by an **AsyKeyGenerator**. 1189 1190> **NOTE** 1191> 1192> The **pubKey** and **priKey** objects in the **KeyPair** object are defined as one parameter in **KeyPair**. When **KeyPair** leaves the scope, its internal objects may be destructed. <br>The service must reference the **KeyPair** object instead of the **pubKey** or **priKey** object. 1193 1194### Attributes 1195 1196**System capability**: SystemCapability.Security.CryptoFramework 1197 1198| Name | Type | Readable| Writable| Description | 1199| ------- | ------ | ---- | ---- | ------------ | 1200| priKey | [PriKey](#prikey) | Yes | No | Private key. | 1201| pubKey | [PubKey](#pubkey) | Yes | No | Public key. | 1202 1203 1204## cryptoFramework.createSymKeyGenerator 1205 1206createSymKeyGenerator(algName : string) : SymKeyGenerator 1207 1208Creates a **symKeyGenerator** instance based on the specified algorithm. 1209 1210For details about the supported specifications, see [Key Generation Specifications](../../security/cryptoFramework-overview.md#key-generation-specifications). 1211 1212**System capability**: SystemCapability.Security.CryptoFramework 1213 1214**Parameters** 1215 1216| Name | Type | Mandatory| Description | 1217| ------- | ------ | ---- | ------------------------------------------------------------ | 1218| algName | string | Yes | Algorithm used to create the **symKeyGenerator** instance.<br>For details, see "String Parameter" in [Key Generation Specifications](../../security/cryptoFramework-overview.md#key-generation-specifications). | 1219 1220**Return value** 1221 1222| Type | Description | 1223| ----------------------------------- | -------------------------- | 1224| [SymKeyGenerator](#symkeygenerator) | **symKeyGenerator** instance created.| 1225 1226**Example** 1227 1228```js 1229import cryptoFramework from '@ohos.security.cryptoFramework'; 1230let symKeyGenerator = cryptoFramework.createSymKeyGenerator('3DES192'); 1231``` 1232 1233## SymKeyGenerator 1234 1235Provides APIs for using the **symKeyGenerator**. 1236 1237Before using any API of the **SymKeyGenerator** class, you must create a **symKeyGenerator** instance by using [createSymKeyGenerator](#cryptoframeworkcreatesymkeygenerator). 1238 1239### Attributes 1240 1241**System capability**: SystemCapability.Security.CryptoFramework 1242 1243| Name | Type | Readable| Writable| Description | 1244| ------- | ------ | ---- | ---- | ------------------------------ | 1245| algName | string | Yes | No | Algorithm used by the **symKeyGenerator**.| 1246 1247### generateSymKey 1248 1249generateSymKey(callback : AsyncCallback\<SymKey>) : void 1250 1251Generates a symmetric key randomly. This API uses an asynchronous callback to return the result. 1252 1253This API can be used only after a **symKeyGenerator** instance is created by using [createSymKeyGenerator](#cryptoframeworkcreatesymkeygenerator). 1254 1255**RAND_priv_bytes()** of OpenSSL can be used to generate random keys. 1256 1257**System capability**: SystemCapability.Security.CryptoFramework 1258 1259**Parameters** 1260 1261| Name | Type | Mandatory| Description | 1262| -------- | --------------------------------- | ---- | ------------------------------------------------------------ | 1263| 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.| 1264 1265**Error codes** 1266 1267| ID| Error Message | 1268| -------- | ------------- | 1269| 17620001 | memory error. | 1270 1271**Example** 1272 1273```js 1274import cryptoFramework from '@ohos.security.cryptoFramework'; 1275let symAlgName = '3DES192'; 1276let symKeyGenerator = cryptoFramework.createSymKeyGenerator(symAlgName); 1277symKeyGenerator.generateSymKey((err, symKey) => { 1278 if (err) { 1279 console.error(`Generate symKey failed, ${err.code}, ${err.message}`); 1280 } else { 1281 console.info(`Generate symKey success, algName: ${symKey.algName}`); 1282 } 1283}) 1284``` 1285 1286### generateSymKey 1287 1288generateSymKey() : Promise\<SymKey> 1289 1290Generates a symmetric key randomly. This API uses a promise to return the result. 1291 1292This API can be used only after a **symKeyGenerator** instance is created by using [createSymKeyGenerator](#cryptoframeworkcreatesymkeygenerator). 1293 1294**RAND_priv_bytes()** of OpenSSL can be used to generate random keys. 1295 1296**System capability**: SystemCapability.Security.CryptoFramework 1297 1298**Return value** 1299 1300| Type | Description | 1301| --------------------------- | --------------------------------- | 1302| Promise\<[SymKey](#symkey)> | Promise used to return the symmetric key generated.| 1303 1304**Error codes** 1305 1306| ID| Error Message | 1307| -------- | ------------- | 1308| 17620001 | memory error. | 1309 1310**Example** 1311 1312```js 1313import cryptoFramework from '@ohos.security.cryptoFramework'; 1314let symAlgName = 'AES128'; 1315let symKeyGenerator = cryptoFramework.createSymKeyGenerator(symAlgName); 1316symKeyGenerator.generateSymKey() 1317.then(symKey => { 1318 console.info(`Generate symKey success, algName: ${symKey.algName}`); 1319}, error => { 1320 console.error(`Generate symKey failed, ${error.code}, ${error.message}`); 1321}) 1322``` 1323 1324### convertKey 1325 1326convertKey(key : DataBlob, callback : AsyncCallback\<SymKey>) : void 1327 1328Converts data into a symmetric key. This API uses an asynchronous callback to return the result. <br>This API can be used only after a **symKeyGenerator** instance is created by using [createSymKeyGenerator](#cryptoframeworkcreatesymkeygenerator). 1329 1330**System capability**: SystemCapability.Security.CryptoFramework 1331 1332**Parameters** 1333 1334| Name | Type | Mandatory| Description | 1335| -------- | --------------------------------- | ---- | ------------------------------------------------------------ | 1336| key | [DataBlob](#datablob) | Yes | Data to convert. | 1337| 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.| 1338 1339**Error codes** 1340 1341| ID| Error Message | 1342| -------- | --------------------------------------------------- | 1343| 17620001 | memory error. | 1344 1345**Example** 1346 1347```js 1348import cryptoFramework from '@ohos.security.cryptoFramework'; 1349 1350function genKeyMaterialBlob() { 1351 let arr = [ 1352 0xba, 0x3d, 0xc2, 0x71, 0x21, 0x1e, 0x30, 0x56, 1353 0xad, 0x47, 0xfc, 0x5a, 0x46, 0x39, 0xee, 0x7c, 1354 0xba, 0x3b, 0xc2, 0x71, 0xab, 0xa0, 0x30, 0x72]; // keyLen = 192 (24 bytes) 1355 let keyMaterial = new Uint8Array(arr); 1356 return {data : keyMaterial}; 1357} 1358 1359let symAlgName = '3DES192'; 1360let symKeyGenerator = cryptoFramework.createSymKeyGenerator(symAlgName); 1361let keyMaterialBlob = genKeyMaterialBlob(); 1362symKeyGenerator.convertKey(keyMaterialBlob, (err, symKey) => { 1363 if (err) { 1364 console.error(`Convert symKey failed, ${err.code}, ${err.message}`); 1365 } else { 1366 console.info(`Convert symKey success, algName: ${symKey.algName}`); 1367 } 1368}) 1369``` 1370 1371### convertKey 1372 1373convertKey(key : DataBlob) : Promise\<SymKey> 1374 1375Converts data into a symmetric key. This API uses a promise to return the result. <br>This API can be used only after a **symKeyGenerator** instance is created by using [createSymKeyGenerator](#cryptoframeworkcreatesymkeygenerator). 1376 1377**System capability**: SystemCapability.Security.CryptoFramework 1378 1379**Parameters** 1380 1381| Name| Type | Mandatory| Description | 1382| ---- | --------------------- | ---- | -------------------- | 1383| key | [DataBlob](#datablob) | Yes | Data to convert.| 1384 1385**Return value** 1386 1387| Type | Description | 1388| --------------------------- | --------------------------------- | 1389| Promise\<[SymKey](#symkey)> | Promise used to return the symmetric key generated.| 1390 1391**Error codes** 1392 1393| ID| Error Message | 1394| -------- | --------------------------------------------- | 1395| 17620001 | memory error. | 1396 1397**Example** 1398 1399```js 1400import cryptoFramework from '@ohos.security.cryptoFramework'; 1401 1402function genKeyMaterialBlob() { 1403 let arr = [ 1404 0xba, 0x3d, 0xc2, 0x71, 0x21, 0x1e, 0x30, 0x56, 1405 0xad, 0x47, 0xfc, 0x5a, 0x46, 0x39, 0xee, 0x7c, 1406 0xba, 0x3b, 0xc2, 0x71, 0xab, 0xa0, 0x30, 0x72]; // keyLen = 192 (24 bytes) 1407 let keyMaterial = new Uint8Array(arr); 1408 return {data : keyMaterial}; 1409} 1410 1411let symAlgName = '3DES192'; 1412let symKeyGenerator = cryptoFramework.createSymKeyGenerator(symAlgName); 1413let keyMaterialBlob = genKeyMaterialBlob(); 1414symKeyGenerator.convertKey(keyMaterialBlob) 1415.then(symKey => { 1416 console.info(`Convert symKey success, algName: ${symKey.algName}`); 1417}, error => { 1418 console.error(`Convert symKey failed, ${error.code}, ${error.message}`); 1419}) 1420``` 1421 1422## cryptoFramework.createAsyKeyGenerator 1423 1424createAsyKeyGenerator(algName : string) : AsyKeyGenerator 1425 1426Creates an **AsyKeyGenerator** instance based on the specified algorithm. 1427 1428For details about the supported specifications, see [Key Generation Specifications](../../security/cryptoFramework-overview.md#key-generation-specifications). 1429 1430**System capability**: SystemCapability.Security.CryptoFramework 1431 1432**Parameters** 1433 1434| Name | Type | Mandatory| Description | 1435| ------- | ------ | ---- | -------------------------------- | 1436| algName | string | Yes | Algorithm used to create the **symkeyGenerator**.| 1437 1438**Return value** 1439 1440| Type | Description | 1441| --------------- | ---------------------------- | 1442| [AsyKeyGenerator](#asykeygenerator) | **AsyKeyGenerator** instance created.| 1443 1444**Example** 1445 1446```javascript 1447import cryptoFramework from "@ohos.security.cryptoFramework" 1448 1449let asyKeyGenerator = cryptoFramework.createAsyKeyGenerator("ECC256"); 1450``` 1451 1452## AsyKeyGenerator 1453 1454Provides APIs for using the **AsKeyGenerator**. Before using any API of the **AsKeyGenerator** class, you must create an **AsyKeyGenerator** instance by using **createAsyKeyGenerator()**. 1455 1456### Attributes 1457 1458**System capability**: SystemCapability.Security.CryptoFramework 1459 1460| Name | Type | Readable| Writable| Description | 1461| ------- | ------ | ---- | ---- | -------------------------------- | 1462| algName | string | Yes | No | Algorithm used by the **AsKeyGenerator**.| 1463 1464### generateKeyPair 1465 1466generateKeyPair(callback : AsyncCallback\<KeyPair>) : void; 1467 1468Generates a key pair randomly. This API uses an asynchronous callback to return the result. 1469 1470**System capability**: SystemCapability.Security.CryptoFramework 1471 1472**Parameters** 1473 1474| Name | Type | Mandatory| Description | 1475| -------- | ----------------------- | ---- | ------------------------------ | 1476| callback | AsyncCallback\<[KeyPair](#keypair)> | Yes | Callback invoked to return the key pair obtained.| 1477 1478**Error codes** 1479 1480| ID| Error Message | 1481| -------- | ---------------------- | 1482| 17620001 | memory error. | 1483 1484**Example** 1485 1486```javascript 1487import cryptoFramework from "@ohos.security.cryptoFramework" 1488 1489let asyKeyGenerator = cryptoFramework.createAsyKeyGenerator("ECC256"); 1490asyKeyGenerator.generateKeyPair((err, keyPair) => { 1491 if (err) { 1492 console.error("generateKeyPair: error."); 1493 return; 1494 } 1495 console.info("generateKeyPair: success."); 1496}) 1497``` 1498 1499 1500### generateKeyPair 1501 1502generateKeyPair() : Promise\<KeyPair> 1503 1504Generates a key pair randomly. This API uses a promise to return the result. 1505 1506**System capability**: SystemCapability.Security.CryptoFramework 1507 1508**Return value** 1509 1510| Type | Description | 1511| ----------------- | --------------------------------- | 1512| Promise\<[KeyPair](#keypair)> | Promise used to return the key pair generated.| 1513 1514**Error codes** 1515 1516| ID| Error Message | 1517| -------- | ---------------------- | 1518| 17620001 | memory error. | 1519 1520**Example** 1521 1522```javascript 1523import cryptoFramework from "@ohos.security.cryptoFramework" 1524 1525let asyKeyGenerator = cryptoFramework.createAsyKeyGenerator("ECC256"); 1526let keyGenPromise = asyKeyGenerator.generateKeyPair(); 1527keyGenPromise.then( keyPair => { 1528 console.info("generateKeyPair success."); 1529}).catch(error => { 1530 console.error("generateKeyPair error."); 1531}); 1532``` 1533 1534### convertKey 1535 1536convertKey(pubKey : DataBlob, priKey : DataBlob, callback : AsyncCallback\<KeyPair\>) : void 1537 1538Converts data into an asymmetric key. This API uses an asynchronous callback to return the result. For more information, see **Key Conversion**. 1539 1540**System capability**: SystemCapability.Security.CryptoFramework 1541 1542**Parameters** 1543 1544| Name | Type | Mandatory| Description | 1545| -------- | ----------- | ---- | ------------------------------ | 1546| pubKey | [DataBlob](#datablob) | Yes | Public key material to convert. If no public key is required, set this parameter to **null**. | 1547| priKey | [DataBlob](#datablob) | Yes | Private key material to convert. If no private key is required, set this parameter to **null**. | 1548| callback | AsyncCallback\<[KeyPair](#keypair)> | Yes | Callback invoked to return the key pair obtained.| 1549 1550**Error codes** 1551 1552| ID| Error Message | 1553| -------- | ---------------------- | 1554| 17620001 | memory error. | 1555 1556**Example** 1557 1558```javascript 1559import cryptoFramework from "@ohos.security.cryptoFramework" 1560let pubKey; // Public key data in DER format complying with X.509 specifications. The data is omitted here. 1561let priKey; // Private key data in DER format complying with PKCS#8 specifications. The data is omitted here. 1562let asyKeyGenerator = cryptoFramework.createAsyKeyGenerator("ECC256"); 1563asyKeyGenerator.convertKey(pubKey, priKey, (err, keyPair) => { 1564 if (err) { 1565 console.error("convertKey: error."); 1566 return; 1567 } 1568 console.info("convertKey: success."); 1569}) 1570``` 1571 1572### convertKey 1573 1574convertKey(pubKey : DataBlob, priKey : DataBlob) : Promise\<KeyPair> 1575 1576Converts data into an asymmetric key. This API uses a promise to return the result. For more information, see **Key Conversion**. 1577 1578**System capability**: SystemCapability.Security.CryptoFramework 1579 1580**Parameters** 1581 1582| Name | Type | Mandatory| Description | 1583| ------ | -------- | ---- | ---------------- | 1584| pubKey | DataBlob | Yes | Public key material to convert. If no public key is required, set this parameter to **null**.| 1585| priKey | DataBlob | Yes | Private key material to convert. If no private key is required, set this parameter to **null**.| 1586 1587**Return value** 1588 1589| Type | Description | 1590| ----------------- | --------------------------------- | 1591| Promise\<[KeyPair](#keypair)> | Promise used to return the key pair obtained. | 1592 1593**Error codes** 1594 1595| ID| Error Message | 1596| -------- | ---------------------- | 1597| 17620001 | memory error. | 1598 1599**Example** 1600 1601```javascript 1602import cryptoFramework from "@ohos.security.cryptoFramework" 1603 1604let asyKeyGenerator = cryptoFramework.createAsyKeyGenerator("ECC256"); 1605let pubKey; // pubKey is a public key generated by the asymmetric key generator. The generation process is omitted here. 1606let priKey; // priKey is a private key generated by the asymmetric key generator. The generation process is omitted here. 1607let keyGenPromise = asyKeyGenerator.convertKey(pubKey, priKey); 1608keyGenPromise.then( keyPair => { 1609 console.info("convertKey success."); 1610}).catch(error => { 1611 console.error("convertKey error."); 1612}); 1613``` 1614 1615**Key Conversion** 1616 1617- If **getEncoded()** is called to obtain a public key and a private key (RSA and ECC), binary data in X.509 format and binary data in PKCS #8 format are returned, respectively. The data can be used for cross-application transfer or persistent storage. 1618- When **convertKey()** is called to convert binary data into an asymmetric key pair, the public key material must comply with the ASN.1 syntax, X.509 specifications, and DER encoding format, and the private key material must comply with the ASN.1 syntax, PKCS #8 specifications, and DER encoding format. 1619- 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. 1620 1621## cryptoFramework.createCipher 1622 1623createCipher(transformation : string) : Cipher 1624 1625Creates a [Cipher](#cipher) instance based on the specified algorithm. 1626 1627For details about the supported specifications, see [Encryption and Decryption Specifications](../../security/cryptoFramework-overview.md#encryption-and-decryption-specifications). 1628 1629**System capability**: SystemCapability.Security.CryptoFramework 1630 1631**Parameters** 1632 1633| Name | Type | Mandatory| Description | 1634| -------------- | ------ | ---- | ------------------------------------------------------------ | 1635| transformation | string | Yes | Combination of the algorithm name (including the key length), encryption mode, and padding algorithm of the **Cipher** instance to create.<br>For details, see **Algorithm String** in [Encryption and Decryption Specifications](../../security/cryptoFramework-overview.md#encryption-and-decryption-specifications). | 1636 1637> **NOTE** 1638> - In symmetric encryption and decryption, the implementation of PKCS #5 is the same as that of PKCS #7. PKCS #5 and PKCS #7 use the same padding length and block length. That is, data is padded with 8 bytes in 3DES and 16 bytes in AES. **noPadding** indicates that no padding is performed. <br>You need to understand the differences between different block cipher modes and set parameter correctly. For example, padding is required for ECB and CBC. Otherwise, the plaintext length must be 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. 1639> - If RSA is used for asymmetric encryption and decryption, two **Cipher** objects must be created to perform encryption and decryption separately. 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. 1640 1641**Return value** 1642 1643| Type | Description | 1644| ----------------- | ------------------------ | 1645| [Cipher](#cipher) | [Cipher](#cipher) instance created.| 1646 1647**Example** 1648 1649```javascript 1650import cryptoFramework from "@ohos.security.cryptoFramework" 1651 1652let cipherAlgName = '3DES192|ECB|PKCS7'; 1653var cipher; 1654try { 1655 cipher = cryptoFramework.createCipher(cipherAlgName); 1656 console.info(`cipher algName: ${cipher.algName}`); 1657} catch (error) { 1658 console.error(`createCipher failed, ${error.code}, ${error.message}`); 1659} 1660``` 1661 1662## Cipher 1663 1664Provides APIs for cipher operations. The [init()](#init-2), [update()](#update-4), and [doFinal()](#dofinal-2) APIs in this class are called in sequence to implement symmetric encryption/decryption and asymmetric encryption/decryption. 1665 1666For details about the complete encryption and decryption process, see [Encrypting and Decrypting Data](../../security/cryptoFramework-guidelines.md#encrypting-and-decrypting-data). 1667 1668A complete symmetric encryption/decryption process is slightly different from the asymmetric encryption/decryption process. 1669 1670- In symmetric encryption and decryption, **init()** and **doFinal()** are mandatory. **update()** is optional and can be called multiple times to encrypt or decrypt big data by segment. After **doFinal()** is called to complete an encryption/decryption operation, **init()** can be called to start a new encryption/decryption operation. 1671- In RSA 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 by segment. **init()** cannot be called repeatedly. If the encryption/decryption mode or padding mode is changed, a new **Cipher** object must be created. 1672 1673### Attributes 1674 1675**System capability**: SystemCapability.Security.CryptoFramework 1676 1677 1678| Name | Type | Readable| Writable| Description | 1679| ------- | ------ | ---- | ---- | ---------------------------- | 1680| algName | string | Yes | No | Algorithm.| 1681 1682### init 1683 1684init(opMode : CryptoMode, key : Key, params : ParamsSpec, callback : AsyncCallback\<void>) : void 1685 1686Initializes a [cipher](#cipher) instance. This API uses an asynchronous callback to return the result. 1687 1688This API can be used only after a [Cipher](#cipher) instance is created by using [createCipher](#cryptoframeworkcreatecipher). 1689 1690**System capability**: SystemCapability.Security.CryptoFramework 1691 1692**Parameters** 1693 1694| Name | Type | Mandatory| Description | 1695| -------- | ------------------------- | ---- | ------------------------------------------------------------ | 1696| opMode | [CryptoMode](#cryptomode) | Yes | Operation (encryption or decryption) to perform. | 1697| key | [Key](#key) | Yes | Key for encryption or decryption. | 1698| params | [ParamsSpec](#paramsspec) | Yes | Parameters for encryption or decryption. For algorithm modes without parameters (such as ECB), **null** can be passed in.| 1699| callback | AsyncCallback\<void> | Yes | Callback invoked to return the result. If the initialization is successful, **err** is **undefined**. Otherwise, **err** is an error object. | 1700 1701**Error codes** 1702 1703| ID| Error Message | 1704| -------- | --------------------------------------------------------- | 1705| 17620001 | memory error. | 1706| 17620002 | runtime error. | 1707| 17630001 | crypto operation error.| 1708 1709**Example** 1710 1711```js 1712import cryptoFramework from '@ohos.security.cryptoFramework'; 1713let symKey; // The process of generating the symmetric key is omitted here. 1714let cipher; // The process of creating a Cipher instance is omitted here. 1715 1716cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, symKey, null, (err, ) => { 1717 if (err) { 1718 console.error(`Failed to init cipher, ${err.code}, ${err.message}`); 1719 } else { 1720 console.info(`Init cipher success`); 1721 // Perform subsequent operations such as update. 1722 } 1723}) 1724``` 1725 1726### init 1727 1728init(opMode : CryptoMode, key : Key, params : ParamsSpec) : Promise\<void> 1729 1730Initializes a [cipher](#cipher) instance. This API uses a promise to return the result. 1731 1732This API can be used only after a [Cipher](#cipher) instance is created by using [createCipher](#cryptoframeworkcreatecipher). 1733 1734**System capability**: SystemCapability.Security.CryptoFramework 1735 1736**Parameters** 1737 1738| Name | Type | Mandatory| Description | 1739| ------ | ------------------------- | ---- | ------------------------------------------------------------ | 1740| opMode | [CryptoMode](#cryptomode) | Yes | Operation (encryption or decryption) to perform. | 1741| key | [Key](#key) | Yes | Key for encryption or decryption. | 1742| params | [ParamsSpec](#paramsspec) | Yes | Parameters for encryption or decryption. For algorithm modes without parameters (such as ECB), **null** can be passed in.| 1743 1744**Return value** 1745 1746| Type | Description | 1747| -------------- | -------------------------------------- | 1748| Promise\<void> | Promise that returns no value.| 1749 1750**Error codes** 1751 1752| ID| Error Message | 1753| -------- | ------------------------------------------------- | 1754| 17620001 | memory error. | 1755| 17620002 | runtime error. | 1756| 17630001 | crypto operation error.| 1757 1758**Example** 1759 1760```js 1761import cryptoFramework from '@ohos.security.cryptoFramework'; 1762let symKey; // The process of generating the symmetric key is omitted here. 1763let cipher; // The process of creating a Cipher instance is omitted here. 1764cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, symKey, null) 1765.then(() => { 1766 console.info(`Init cipher success`); 1767 // Perform subsequent operations such as update. 1768}, error => { 1769 console.error(`Failed to init cipher, ${error.code}, ${error.message}`); 1770}) 1771``` 1772 1773### update 1774 1775update(data : DataBlob, callback : AsyncCallback\<DataBlob>) : void 1776 1777Updates the data to encrypt or decrypt by segment. This API uses an asynchronous callback to return the encrypted or decrypted data. 1778 1779This API can be called only after the [Cipher](#cipher) instance is initialized by using [init()](init-2). 1780 1781> **NOTE** 1782> - The **update()** and [doFinal()](#dofinal-2) results vary with the block mode you use. If you are not familiar with the block modes for symmetric encryption and decryption, add a judgment to determine whether the result of each **update()** and **doFinal()** is null. If the result is not null, obtain the data to concatenate the complete ciphertext or plaintext.<br>For example, in ECB and CBC modes, data is encrypted or decrypted by block no matter whether the data passed in by **update()** is an integer multiple of the block length, and the encrypted/decrypted block data generated by this **update()** is output. <br>That is, data is output by **update()** as long as the input data is of the block size. 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. 1783> - **update()** can be called multiple times or not be called ([doFinal()](#dofinal-2) is called after [init](#init-2)), depending on the size of the data to encrypt or decrypt. <br>The algorithm library does not set a limit on the amount of data that can be passed in by **updated()** (once or accumulatively). For symmetric encryption and decryption of a large amount of data, you are advised to call **update()** multiple times to pass in the data by segment. <br>For details about the sample code for calling **update()** multiple times in AES, see [Encrypting and Decrypting Data](../../security/cryptoFramework-guidelines.md#encrypting-and-decrypting-data). 1784> - RSA asymmetric encryption and decryption do not support **update()**. 1785 1786**System capability**: SystemCapability.Security.CryptoFramework 1787 1788**Parameters** 1789 1790| Name | Type | Mandatory| Description | 1791| -------- | ------------------------------------- | ---- | ------------------------------------------------------------ | 1792| data | [DataBlob](#datablob) | Yes | Data to encrypt or decrypt. It cannot be **null** or {data:Uint8Array (null)}. | 1793| 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.| 1794 1795**Error codes** 1796 1797| ID| Error Message | 1798| -------- | ------------------------------------------- | 1799| 17620001 | memory error. | 1800| 17620002 | runtime error. | 1801| 17630001 | crypto operation error. | 1802 1803**Example** 1804 1805```js 1806import cryptoFramework from '@ohos.security.cryptoFramework'; 1807 1808function stringToUint8Array(str) { 1809 let arr = []; 1810 for (let i = 0, j = str.length; i < j; ++i) { 1811 arr.push(str.charCodeAt(i)); 1812 } 1813 return new Uint8Array(arr); 1814} 1815 1816let cipher; // The process of creating a Cipher instance is omitted here. 1817// The init() process is omitted here. 1818let plainText = {data : stringToUint8Array('this is test!')}; 1819cipher.update(plainText, (err, output) => { // Example of the encryption process. 1820 if (err) { 1821 console.error(`Failed to update cipher`); 1822 } else { 1823 console.info(`Update cipher success`); 1824 if (output != null) { 1825 // Concatenate output.data to the ciphertext. 1826 } 1827 // Perform subsequent operations such as doFinal(). 1828 } 1829}) 1830``` 1831 1832### update 1833 1834update(data : DataBlob) : Promise\<DataBlob> 1835 1836Updates the data to encrypt or decrypt by segment. This API uses a promise to return the encrypted or decrypted data. <br>This API can be called only after the [Cipher](#cipher) instance is initialized by using [init()](init-2). 1837 1838> **NOTE** 1839> - The **update()** and [doFinal()](#dofinal-2) results vary with the block mode you use. If you are not familiar with the block modes for symmetric encryption and decryption, add a judgment to determine whether the result of each **update()** and **doFinal()** is null. If the result is not null, obtain the data to concatenate the complete ciphertext or plaintext.<br>For example, in ECB and CBC modes, data is encrypted or decrypted by block no matter whether the data passed in by **update()** is an integer multiple of the block length, and the encrypted/decrypted block data generated by this **update()** is output. <br>That is, data is output as long as the data passed in by **update()** is of the block size. 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. 1840> - **update()** can be called multiple times or not be called ([doFinal()](#dofinal-2) is called after [init](#init-2)), depending on the size of the data to encrypt or decrypt. <br>The algorithm library does not set a limit on the amount of data that can be passed in by **updated()** (once or accumulatively). For symmetric encryption and decryption of a large amount of data, you are advised to call **update()** multiple times to pass in the data by segment. For details about the sample code for calling **update()** multiple times in AES, see [Encrypting and Decrypting Data](../../security/cryptoFramework-guidelines.md#encrypting-and-decrypting-data). 1841> - RSA asymmetric encryption and decryption do not support **update()**. 1842 1843**System capability**: SystemCapability.Security.CryptoFramework 1844 1845**Parameters** 1846 1847| Name| Type | Mandatory| Description | 1848| ---- | --------------------- | ---- | -------------------- | 1849| data | [DataBlob](#datablob) | Yes | Data to encrypt or decrypt. It cannot be **null** or {data:Uint8Array (null)}.| 1850 1851**Return value** 1852 1853| Type | Description | 1854| ------------------------------- | ------------------------------------------------ | 1855| Promise\<[DataBlob](#datablob)> | Promise used to return the **DataBlob** (containing the encrypted or decrypted data).| 1856 1857**Error codes** 1858 1859| ID| Error Message | 1860| -------- | -------------------------------------------- | 1861| 17620001 | memory error. | 1862| 17620002 | runtime error. | 1863| 17630001 | crypto operation error. | 1864 1865**Example** 1866 1867```js 1868import cryptoFramework from '@ohos.security.cryptoFramework'; 1869 1870function stringToUint8Array(str) { 1871 let arr = []; 1872 for (let i = 0, j = str.length; i < j; ++i) { 1873 arr.push(str.charCodeAt(i)); 1874 } 1875 return new Uint8Array(arr); 1876} 1877 1878let cipher; // The process of creating a Cipher instance is omitted here. 1879// The init() process is omitted here. 1880let plainText = {data : stringToUint8Array('this is test!')}; 1881cipher.update(plainText) 1882.then((output) => { 1883 console.info(`Update cipher success.`); 1884 if (output != null) { 1885 // Concatenate output.data to the ciphertext. 1886 } 1887 // Perform subsequent operations such as doFinal(). 1888}, error => { 1889 console.info(`Update cipher failed.`); 1890}) 1891``` 1892 1893### doFinal 1894 1895doFinal(data : DataBlob, callback : AsyncCallback\<DataBlob>) : void 1896 1897(1) Encrypts or decrypts the remaining data (generated by the block ciper 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()**. 1898 1899The output of **doFinal()** varies with the symmetric encryption/decryption mode in use. 1900 1901- Symmetric encryption in GCM and CCM mode: The result consists of the ciphertext and **authTag** (the last 16 bytes for GCM and the last 12 bytes for CCM). If **null** is passed in by **data** of **doFinal()**, the result of **doFinal()** is **authTag**. <br>**authTag** must be [GcmParamsSpec](#gcmparamsspec) or [CcmParamsSpec](#ccmparamsspec) used for decryption. The ciphertext is the **data** passed in for decryption. 1902- Symmetric encryption and decryption in other modes and symmetric decryption in GCM and CCM modes: The result is the complete plaintext/ciphertext. 1903 1904(2) Encrypts or decrypts the input data for RSA 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. 1905 1906> **NOTE** 1907> - In symmetric encryption or decryption, calling **doFinal()** means the end of an encryption or decryption process, and the [Cipher](#cipher) instance state will be cleared. To start a new encryption or decryption operation, you must call [init()](#init-2) to pass in a complete parameter list for initialization. <br>For example, if the same symmetric key is used for a **Cipher** instance to perform encryption and then decryption. After the encryption is complete, the **params** in **init** for decryption must be set instead of being **null**. 1908> - If a decryption operation fails, check whether the data to be encrypted and decrypted matches the parameters in **[init](#init-2)**. For the GCM mode, check whether the **authTag** obtained after encryption is obtained from the **GcmParamsSpec** for decryption. 1909> - 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. 1910> - For details about the sample code for calling **doFinal()** multiple times during RSA asymmetric encryption and decryption, see [Encrypting and Decrypting Data](../../security/cryptoFramework-guidelines.md#encrypting-and-decrypting-data). 1911 1912**System capability**: SystemCapability.Security.CryptoFramework 1913 1914**Parameters** 1915 1916| Name | Type | Mandatory| Description | 1917| -------- | ------------------------------------- | ---- | ------------------------------------------------------------ | 1918| data | [DataBlob](#datablob) | Yes | Data to encrypt or decrypt. It can be **null** in symmetric encryption or decryption, but cannot be {data:Uint8Array(null)}. | 1919| 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.| 1920 1921**Error codes** 1922 1923| ID| Error Message | 1924| -------- | ----------------------- | 1925| 17620001 | memory error. | 1926| 17620002 | runtime error. | 1927| 17630001 | crypto operation error. | 1928 1929**Example** 1930 1931```js 1932import cryptoFramework from '@ohos.security.cryptoFramework'; 1933 1934let cipher; // The process of creating a Cipher instance is omitted here. 1935let data; // The process of preparing the data to encrypt or decrypt is omitted here. 1936// The init() and update() processes are omitted here. 1937cipher.doFinal(data, (err, output) => { 1938 if (err) { 1939 console.error(`Failed to finalize cipher, ${err.code}, ${err.message}`); 1940 } else { 1941 console.info(`Finalize cipher success`); 1942 if (output != null) { 1943 // Concatenate output.data to obtain the complete plaintext/ciphertext (and authTag). 1944 } 1945 } 1946}) 1947``` 1948 1949### doFinal 1950 1951doFinal(data : DataBlob) : Promise\<DataBlob> 1952 1953(1) Encrypts or decrypts the remaining data (generated by the block ciper mode) and the data passed in by **doFinal()** to finalize the symmetric encryption or decryption. This API uses a promise to return the encrypted or decrypted data. <br>If a small amount of data needs to be encrypted or decrypted, you can use **doFinal()** to pass in data without using **update()**. If all the data has been passed in by [update()](#update-4), you can pass in **null** in **data** of **doFinal()**. 1954 1955The output of **doFinal()** varies with the symmetric encryption/decryption mode in use. 1956 1957- Symmetric encryption in GCM and CCM mode: The result consists of the ciphertext and **authTag** (the last 16 bytes for GCM and the last 12 bytes for CCM). If **null** is passed in by **data** of **doFinal()**, the result of **doFinal()** is **authTag**. <br>**authTag** must be [GcmParamsSpec](#gcmparamsspec) or [CcmParamsSpec](#ccmparamsspec) used for decryption. The ciphertext is the **data** passed in for decryption. 1958- Symmetric encryption and decryption in other modes and symmetric decryption in GCM and CCM modes: The result is the complete plaintext/ciphertext. 1959 1960(2) Encrypts or decrypts the input data for RSA 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. 1961 1962> **NOTE** 1963> - In symmetric encryption or decryption, calling **doFinal()** means the end of an encryption or decryption process, and the [Cipher](#cipher) instance state will be cleared. To start a new encryption or decryption operation, you must call [init()](#init-2) to pass in a complete parameter list for initialization. <br>For example, if the same symmetric key is used for a **Cipher** instance to perform encryption and then decryption. After the encryption is complete, the **params** in **init** for decryption must be set instead of being **null**. 1964> - If a decryption fails, check whether the data to be encrypted and decrypted matches the parameters in **[init](#init-2)**. For the GCM mode, check whether the **authTag** obtained after encryption is obtained from the **GcmParamsSpec** for decryption. 1965> - 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. 1966> - For details about the sample code for calling **doFinal()** multiple times during RSA asymmetric encryption and decryption, see [Encrypting and Decrypting Data](../../security/cryptoFramework-guidelines.md#encrypting-and-decrypting-data). 1967 1968**System capability**: SystemCapability.Security.CryptoFramework 1969 1970**Parameters** 1971 1972| Name| Type | Mandatory| Description | 1973| ---- | --------------------- | ---- | -------------------- | 1974| data | [DataBlob](#datablob) | Yes | Data to encrypt or decrypt. It can be **null**, but cannot be {data:Uint8Array(null)}.| 1975 1976**Return value** 1977 1978| Type | Description | 1979| ------------------------------- | ------------------------------------------------ | 1980| Promise\<[DataBlob](#datablob)> | Promise used to return the **DataBlob**, which is the encryption or decryption result of the remaining data.| 1981 1982**Error codes** 1983 1984| ID| Error Message | 1985| -------- | -------------------------------------------- | 1986| 17620001 | memory error. | 1987| 17620002 | runtime error. | 1988| 17630001 | crypto operation error. | 1989 1990**Example** 1991 1992```js 1993import cryptoFramework from '@ohos.security.cryptoFramework'; 1994 1995let cipher; // The process of creating a Cipher instance is omitted here. 1996let data; // The process of preparing the data to encrypt or decrypt is omitted here. 1997// The init() and update() processes are omitted here. 1998cipher.doFinal(data) 1999.then(output => { 2000 console.info(`Finalize cipher success`); 2001 if (output != null) { 2002 // Concatenate output.data to obtain the complete plaintext/ciphertext (and authTag). 2003 } 2004}, error => { 2005 console.error(`Failed to finalize cipher, ${error.code}, ${error.message}`); 2006}) 2007``` 2008 2009**RSA encryption example (callback)** 2010 2011```javascript 2012import cryptoFramework from "@ohos.security.cryptoFramework" 2013 2014function stringToUint8Array(str) { 2015 let arr = []; 2016 for (let i = 0, j = str.length; i < j; ++i) { 2017 arr.push(str.charCodeAt(i)); 2018 } 2019 return new Uint8Array(arr); 2020} 2021 2022let rsaGenerator = cryptoFramework.createAsyKeyGenerator("RSA1024|PRIMES_2"); 2023let cipher = cryptoFramework.createCipher("RSA1024|PKCS1"); 2024rsaGenerator.generateKeyPair(function (err, keyPair) { 2025 let pubKey = keyPair.pubKey; 2026 cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, pubKey, null, function (err, data) { 2027 let plainText = "this is cipher text"; 2028 let input = {data : stringToUint8Array(plainText) }; 2029 cipher.doFinal(input, function (err, data) { 2030 AlertDialog.show({ message : "EncryptOutPut is " + data.data} ); 2031 }); 2032 }); 2033}); 2034``` 2035 2036**RSA encryption example (promise)** 2037 2038```javascript 2039import cryptoFramework from "@ohos.security.cryptoFramework" 2040 2041function stringToUint8Array(str) { 2042 let arr = []; 2043 for (let i = 0, j = str.length; i < j; ++i) { 2044 arr.push(str.charCodeAt(i)); 2045 } 2046 return new Uint8Array(arr); 2047} 2048 2049let rsaGenerator = cryptoFramework.createAsyKeyGenerator("RSA1024|PRIMES_2"); 2050let cipher = cryptoFramework.createCipher("RSA1024|PKCS1"); 2051let keyGenPromise = rsaGenerator.generateKeyPair(); 2052keyGenPromise.then(rsaKeyPair => { 2053 let pubKey = rsaKeyPair.pubKey; 2054 return cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, pubKey, null); // Pass in the private key and DECRYPT_MODE to initialize the decryption mode. 2055}).then(() => { 2056 let plainText = "this is cipher text"; 2057 let input = { data : stringToUint8Array(plainText) }; 2058 return cipher.doFinal(input); 2059}).then(dataBlob => { 2060 console.info("EncryptOutPut is " + dataBlob.data); 2061}); 2062``` 2063 2064> **NOTE**<br> 2065> For more encryption and decryption examples, see [Encrypting and Decrypting Data](../../security/cryptoFramework-guidelines.md#encrypting-and-decrypting data). 2066 2067## cryptoFramework.createSign 2068 2069createSign(algName : string) : Sign 2070 2071Creates a **Sign** instance. 2072 2073For details about the supported specifications, see [Signing and Signature Verification Specifications](../../security/cryptoFramework-overview.md#signing-and-signature-verification-specifications). 2074 2075**System capability**: SystemCapability.Security.CryptoFramework 2076 2077**Parameters** 2078 2079| Name | Type | Mandatory| Description | 2080| ------- | ------ | ---- | ------------------------------------------------------------ | 2081| algName | string | Yes | Signing algorithm to use, which can be RSA or ECC. If RSA PKCS #1 is used, the digest must be set. If RSA PSS is used, the digest and mask digest must be set.| 2082 2083**Return value** 2084 2085| Type| Description | 2086| ---- | -------------------------------- | 2087| Sign | **Sign** instance created.| 2088 2089**Example** 2090 2091```javascript 2092import cryptoFramework from "@ohos.security.cryptoFramework" 2093 2094let signer1 = cryptoFramework.createSign("RSA1024|PKCS1|SHA256"); 2095 2096let singer2 = cryptoFramework.createSign("RSA1024|PSS|SHA256|MGF1_SHA256") 2097``` 2098 2099## Sign 2100 2101Provides APIs for signing. Before using any API of the **Sign** class, you must create a **Sign** instance by using **createSign()**. The **Sign** class does not support repeated initialization. When a new key is used for signing, you must create a new **Sign** object and call **init()** for initialization. 2102 2103The signing mode is determined in **createSign()**, and the key is set by **init()**. 2104 2105If the data to be signed is short, you can use **sign()** to pass in the data for signing after **init()**. 2106 2107If 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. 2108 2109If **update()** is used to pass in data by segment, **data** of **sign()** can be **null**. 2110 2111### Attributes 2112 2113**System capability**: SystemCapability.Security.CryptoFramework 2114 2115| Name | Type | Readable| Writable| Description | 2116| ------- | ------ | ---- | ---- | ---------------------------- | 2117| algName | string | Yes | No | Algorithm to use.| 2118 2119### init 2120 2121init(priKey : PriKey, callback : AsyncCallback\<void>) : void 2122 2123Initializes a **Sign** instance using a private key. This API uses an asynchronous callback to return the result. The **Sign** class does not support repeated calling of **init()**. 2124 2125**System capability**: SystemCapability.Security.CryptoFramework 2126 2127**Parameters** 2128 2129| Name | Type | Mandatory| Description | 2130| -------- | -------------------- | ---- | ---------------- | 2131| priKey | [PriKey](#prikey) | Yes | Private key used for the initialization.| 2132| callback | AsyncCallback\<void> | Yes | Callback invoked to return the result. | 2133 2134**Error codes** 2135 2136| ID| Error Message | 2137| -------- | ---------------------- | 2138| 17620001 | memory error. | 2139| 17620002 | runtime error. | 2140| 17630001 | crypto operation error. | 2141 2142### init 2143 2144init(priKey : PriKey) : Promise\<void> 2145 2146Initializes a **Sign** instance using a private key. This API uses a promise to return the result. The **Sign** class does not support repeated calling of **init()**. 2147 2148**System capability**: SystemCapability.Security.CryptoFramework 2149 2150**Parameters** 2151 2152| Name| Type| Mandatory| Description | 2153| ------ | ---- | ---- | ---------------- | 2154| priKey | [PriKey](#prikey) | Yes | Private key used for the initialization.| 2155 2156**Return value** 2157 2158| Type | Description | 2159| -------------- | ----------- | 2160| Promise\<void> | Promise used to return the result.| 2161 2162**Error codes** 2163 2164| ID| Error Message | 2165| -------- | ---------------------- | 2166| 17620001 | memory error. | 2167| 17620002 | runtime error. | 2168| 17630001 | crypto operation error. | 2169 2170### update 2171 2172update(data : DataBlob, callback : AsyncCallback\<void>) : void 2173 2174Updates the data to be signed. This API uses an asynchronous callback to return the result. 2175 2176> **NOTE**<br> 2177> For details about the sample code for calling **update()** multiple times, see [Generating and Verifying a Signature](../../security/cryptoFramework-guidelines.md#generating-and-verifying-a-signature). 2178 2179**System capability**: SystemCapability.Security.CryptoFramework 2180 2181**Parameters** 2182 2183| Name | Type | Mandatory| Description | 2184| -------- | -------------------- | ---- | ---------- | 2185| data | [DataBlob](#datablob)| Yes | Data to pass in.| 2186| callback | AsyncCallback\<void> | Yes | Callback invoked to return the result. | 2187 2188**Error codes** 2189 2190| ID| Error Message | 2191| -------- | ---------------------- | 2192| 17620001 | memory error. | 2193| 17620002 | runtime error. | 2194| 17630001 | crypto operation error. | 2195 2196### update 2197 2198update(data : DataBlob) : Promise\<void>; 2199 2200Updates the data to be signed. This API uses a promise to return the result. 2201 2202> **NOTE**<br> 2203> For details about the sample code for calling **update()** multiple times, see [Generating and Verifying a Signature](../../security/cryptoFramework-guidelines.md#generating-and-verifying-a-signature). 2204 2205**System capability**: SystemCapability.Security.CryptoFramework 2206 2207**Parameters** 2208 2209| Name| Type | Mandatory| Description | 2210| ------ | -------- | ---- | ---------- | 2211| data | [DataBlob](#datablob) | Yes | Data to pass in.| 2212 2213**Return value** 2214 2215| Type | Description | 2216| -------------- | ----------- | 2217| Promise\<void> | Promise used to return the result.| 2218 2219**Error codes** 2220 2221| ID| Error Message | 2222| -------- | ---------------------- | 2223| 17620001 | memory error. | 2224| 17620002 | runtime error. | 2225| 17630001 | crypto operation error. | 2226 2227### sign 2228 2229sign(data : DataBlob, callback : AsyncCallback\<DataBlob>) : void 2230 2231Signs the data. This API uses an asynchronous callback to return the result. 2232 2233**System capability**: SystemCapability.Security.CryptoFramework 2234 2235**Parameters** 2236 2237| Name | Type | Mandatory| Description | 2238| -------- | -------------------- | ---- | ---------- | 2239| data | [DataBlob](#datablob) | Yes | Data to pass in.| 2240| callback | AsyncCallback\<[DataBlob](#datablob) > | Yes | Callback invoked to return the result. | 2241 2242**Error codes** 2243 2244| ID| Error Message | 2245| -------- | ---------------------- | 2246| 17620001 | memory error. | 2247| 17620002 | runtime error. | 2248| 17630001 | crypto operation error. | 2249 2250### sign 2251 2252sign(data : DataBlob) : Promise\<DataBlob> 2253 2254Signs the data. This API uses a promise to return the result. 2255 2256**System capability**: SystemCapability.Security.CryptoFramework 2257 2258**Parameters** 2259 2260| Name| Type | Mandatory| Description | 2261| ------ | -------- | ---- | ---------- | 2262| data | [DataBlob](#datablob) | Yes | Data to pass in.| 2263 2264**Return value** 2265 2266| Type | Description | 2267| -------------- | ----------- | 2268| Promise\<void> | Promise used to return the result.| 2269 2270**Error codes** 2271 2272| ID| Error Message | 2273| -------- | ---------------------- | 2274| 17620001 | memory error. | 2275| 17620002 | runtime error. | 2276| 17630001 | crypto operation error. | 2277 2278**Callback example**: 2279 2280```javascript 2281import cryptoFramework from "@ohos.security.cryptoFramework" 2282 2283function stringToUint8Array(str) { 2284 var arr = []; 2285 for (var i = 0, j = str.length; i < j; ++i) { 2286 arr.push(str.charCodeAt(i)); 2287 } 2288 var tmpArray = new Uint8Array(arr); 2289 return tmpArray; 2290} 2291 2292let globalKeyPair; 2293let SignMessageBlob; 2294let plan1 = "This is Sign test plan1"; // The first segment of the data. 2295let plan2 = "This is Sign test plan2"; // The second segment of the data. 2296let input1 = { data : stringToUint8Array(plan1) }; 2297let input2 = { data : stringToUint8Array(plan2) }; 2298 2299function signMessageCallback() { 2300 let rsaGenerator = cryptoFramework.createAsyKeyGenerator("RSA1024|PRIMES_2"); 2301 let signer = cryptoFramework.createSign("RSA1024|PKCS1|SHA256"); 2302 rsaGenerator.generateKeyPair(function (err, keyPair) { 2303 globalKeyPair = keyPair; 2304 let priKey = globalKeyPair.priKey; 2305 signer.init(priKey, function (err, data) { 2306 signer.update(input1, function (err, data) { // Add the first segment of the data. 2307 signer.sign(input2, function (err, data) { // Add the second segment of the data, and sign input1 and input2. 2308 SignMessageBlob = data; 2309 AlertDialog.show({message : "res" + SignMessageBlob.data}); 2310 }); 2311 }); 2312 }); 2313 }); 2314} 2315``` 2316 2317**Promise example**: 2318 2319```javascript 2320import cryptoFramework from "@ohos.security.cryptoFramework" 2321 2322function stringToUint8Array(str) { 2323 var arr = []; 2324 for (var i = 0, j = str.length; i < j; ++i) { 2325 arr.push(str.charCodeAt(i)); 2326 } 2327 var tmpArray = new Uint8Array(arr); 2328 return tmpArray; 2329} 2330 2331let globalKeyPair; 2332let SignMessageBlob; 2333let plan1 = "This is Sign test plan1"; // The first segment of the data. 2334let plan2 = "This is Sign test plan2"; // The second segment of the data. 2335let input1 = { data : stringToUint8Array(plan1) }; 2336let input2 = { data : stringToUint8Array(plan2) }; 2337 2338function signMessagePromise() { 2339 let rsaGenerator = cryptoFramework.createAsyKeyGenerator("RSA1024|PRIMES_2"); 2340 let signer = cryptoFramework.createSign("RSA1024|PKCS1|SHA256"); 2341 let keyGenPromise = rsaGenerator.generateKeyPair(); 2342 keyGenPromise.then( keyPair => { 2343 globalKeyPair = keyPair; 2344 let priKey = globalKeyPair.priKey; 2345 return signer.init(priKey); 2346 }).then(() => { 2347 return signer.update(input1); // Add the first segment of the data. 2348 }).then(() => { 2349 return signer.sign(input2); // Add the second segment of the data, and sign input1 and input2. 2350 }).then(dataBlob => { 2351 SignMessageBlob = dataBlob; 2352 console.info("sign output is " + SignMessageBlob.data); 2353 AlertDialog.show({message : "output" + SignMessageBlob.data}); 2354 }); 2355} 2356``` 2357 2358## cryptoFramework.createVerify 2359 2360createVerify(algName : string) : Verify 2361 2362Creates a **Verify** instance. For details about the supported specifications, see [Signing and Signature Verification Specifications](../../security/cryptoFramework-overview.md#signing-and-signature-verification-specifications). 2363 2364**System capability**: SystemCapability.Security.CryptoFramework 2365 2366**Parameters** 2367 2368| Name | Type | Mandatory| Description | 2369| ------- | ------ | ---- | ------------------------------------------------------------ | 2370| algName | string | Yes | Signing algorithm to use, which can be RSA or ECC. If RSA PKCS #1 is used, the digest must be set. If RSA PSS is used, the digest and mask digest must be set.| 2371 2372**Return value** 2373 2374| Type | Description | 2375| ------ | ---------------------------------- | 2376| Verify | **Verify** instance created.| 2377 2378**Example** 2379 2380```javascript 2381import cryptoFramework from "@ohos.security.cryptoFramework" 2382 2383let verifyer1 = cryptoFramework.createVerify("RSA1024|PKCS1|SHA256"); 2384 2385let verifyer2 = cryptoFramework.createVerify("RSA1024|PSS|SHA256|MGF1_SHA256") 2386``` 2387 2388## Verify 2389 2390Provides APIs for signature verification. Before using any API of the **Verify** class, you must create a **Verify** instance by using **createVerify()**. 2391 2392The **Verify** class does not support repeated initialization. When a new key is used for signature verification, you must create a new **Verify** object and call **init()** for initialization. 2393 2394The signature verification mode is determined in **createVerify()**, and key is set by **init()**. 2395 2396If the signature data to be verified is short, you can call **verify()** to pass in the signature data and original data after **init()**. 2397 2398If the signature data to be verified is long, you can use **update()** to pass in the data by segment, and then use **verify()** to verify the entire data. 2399 2400If **update()** is used to pass in data by segment, **data** of **verify()** can be **null**. 2401 2402### Attributes 2403 2404**System capability**: SystemCapability.Security.CryptoFramework 2405 2406| Name | Type | Readable| Writable| Description | 2407| ------- | ------ | ---- | ---- | ---------------------------- | 2408| algName | string | Yes | No | Algorithm to be used for signature verification.| 2409 2410 2411 2412### init 2413 2414init(pubKey : PubKey, callback : AsyncCallback\<void>) : void 2415 2416Initializes the **Verify** instance using a public key. This API uses an asynchronous callback to return the result. 2417 2418**System capability**: SystemCapability.Security.CryptoFramework 2419 2420**Parameters** 2421 2422| Name | Type | Mandatory| Description | 2423| -------- | -------------------- | ---- | ---------------------------- | 2424| pubKey | [PubKey](#pubkey) | Yes | Public key used for the initialization.| 2425| callback | AsyncCallback\<void> | Yes | Callback invoked to return the result. | 2426 2427**Error codes** 2428 2429| ID| Error Message | 2430| -------- | ---------------------- | 2431| 17620001 | memory error. | 2432| 17620002 | runtime error. | 2433| 17630001 | crypto operation error. | 2434 2435### init 2436 2437init(pubKey : PubKey) : Promise\<void> 2438 2439Initializes the **Verify** instance using a public key. This API uses a promise to return the result. 2440 2441**System capability**: SystemCapability.Security.CryptoFramework 2442 2443**Parameters** 2444 2445| Name| Type| Mandatory| Description | 2446| ------ | ---- | ---- | ---------------------------- | 2447| pubKey | [PubKey](#pubkey) | Yes | Public key used for the initialization.| 2448 2449**Return value** 2450 2451| Type | Description | 2452| -------------- | ----------- | 2453| Promise\<void> | Promise used to return the result.| 2454 2455**Error codes** 2456 2457| ID| Error Message | 2458| -------- | ---------------------- | 2459| 17620001 | memory error. | 2460| 17620002 | runtime error. | 2461| 17630001 | crypto operation error. | 2462 2463### update 2464 2465update(data : DataBlob, callback : AsyncCallback\<void>) : void 2466 2467Updates the data for signature verification. This API uses an asynchronous callback to return the result. 2468 2469> **NOTE** 2470> For details about the sample code for calling **update()** multiple times, see [Generating and Verifying a Signature](../../security/cryptoFramework-guidelines.md#generating-and-verifying-a-signature). 2471 2472**System capability**: SystemCapability.Security.CryptoFramework 2473 2474**Parameters** 2475 2476| Name | Type | Mandatory| Description | 2477| -------- | -------------------- | ---- | ---------- | 2478| data | [DataBlob](#datablob)| Yes | Data to pass in.| 2479| callback | AsyncCallback\<void> | Yes | Callback invoked to return the result. | 2480 2481**Error codes** 2482 2483| ID| Error Message | 2484| -------- | ---------------------- | 2485| 17620001 | memory error. | 2486| 17620002 | runtime error. | 2487| 17630001 | crypto operation error. | 2488 2489### update 2490 2491update(data : DataBlob) : Promise\<void>; 2492 2493Updates the data for signature verification. This API uses a promise to return the result. 2494 2495> **NOTE** 2496> For details about the sample code for calling **update()** multiple times, see [Generating and Verifying a Signature](../../security/cryptoFramework-guidelines.md#generating-and-verifying-a-signature). 2497 2498**System capability**: SystemCapability.Security.CryptoFramework 2499 2500**Parameters** 2501 2502| Name| Type | Mandatory| Description | 2503| ------ | -------- | ---- | ---------- | 2504| data | [DataBlob](#datablob) | Yes | Data to pass in.| 2505 2506**Return value** 2507 2508| Type | Description | 2509| -------------- | ----------- | 2510| Promise\<void> | Promise used to return the result.| 2511 2512**Error codes** 2513 2514| ID| Error Message | 2515| -------- | ---------------------- | 2516| 17620001 | memory error. | 2517| 17620002 | runtime error. | 2518| 17630001 | crypto operation error. | 2519 2520### verify 2521 2522verify(data : DataBlob, signatureData : DataBlob, callback : AsyncCallback\<boolean>) : void 2523 2524Verifies a signature. This API uses an asynchronous callback to return the result. 2525 2526**System capability**: SystemCapability.Security.CryptoFramework 2527 2528**Parameters** 2529 2530| Name | Type | Mandatory| Description | 2531| ------------- | -------------------- | ---- | ---------- | 2532| data | [DataBlob](#datablob) | Yes | Data to pass in.| 2533| signatureData | [DataBlob](#datablob) | Yes | Signature data. | 2534| callback | AsyncCallback\<boolean> | Yes | Callback invoked to return the result. | 2535 2536**Error codes** 2537 2538| ID| Error Message | 2539| -------- | ---------------------- | 2540| 17620001 | memory error. | 2541| 17620002 | runtime error. | 2542| 17630001 | crypto operation error. | 2543 2544### verify 2545 2546verify(data : DataBlob, signatureData : DataBlob) : Promise\<boolean> 2547 2548Verifies a signature. This API uses a promise to return the result. 2549 2550**System capability**: SystemCapability.Security.CryptoFramework 2551 2552**Parameters** 2553 2554| Name | Type | Mandatory| Description | 2555| ------------- | -------- | ---- | ---------- | 2556| data | [DataBlob](#datablob) | Yes | Data to pass in.| 2557| signatureData | [DataBlob](#datablob) | Yes | Signature data. | 2558 2559**Return value** 2560 2561| Type | Description | 2562| ----------------- | ---------------------------- | 2563| Promise\<boolean> | Promise used to return the result.| 2564 2565**Error codes** 2566 2567| ID| Error Message | 2568| -------- | ---------------------- | 2569| 17620001 | memory error. | 2570| 17620002 | runtime error. | 2571| 17630001 | crypto operation error. | 2572 2573**Callback example**: 2574 2575```javascript 2576import cryptoFramework from "@ohos.security.cryptoFramework" 2577 2578let globalKeyPair; // globalKeyPair is an asymmetric key object generated by the asymmetric key generator. The generation process is omitted here. 2579let input1 = null; 2580let input2 = null; 2581let signMessageBlob = null; // Signed data, which is omitted here. 2582let verifyer = cryptoFramework.createVerify("RSA1024|PKCS1|SHA25"); 2583verifyer.init(globalKeyPair.pubKey, function (err, data) { 2584 verifyer.update(input1, function(err, data) { 2585 verifyer.verify(input2, signMessageBlob, function(err, data) { 2586 console.info("verify result is " + data); 2587 }) 2588 }); 2589}) 2590``` 2591 2592**Promise example**: 2593 2594```javascript 2595import cryptoFramework from "@ohos.security.cryptoFramework" 2596 2597let globalKeyPair; // globalKeyPair is an asymmetric key object generated by the asymmetric key generator. The generation process is omitted here. 2598let verifyer = cryptoFramework.createVerify("RSA1024|PKCS1|SHA256"); 2599let verifyInitPromise = verifyer.init(globalKeyPair.pubKey); 2600let input1 = null; 2601let input2 = null; 2602let signMessageBlob = null; // Signed data, which is omitted here. 2603verifyInitPromise.then(() => { 2604 return verifyer.update(input1); 2605}).then(() => { 2606 return verifyer.verify(input2, signMessageBlob); 2607}).then(res => { 2608 console.log("Verify result is " + res); 2609}); 2610``` 2611 2612## cryptoFramework.createKeyAgreement 2613 2614createKeyAgreement(algName : string) : KeyAgreement 2615 2616Creates a **KeyAgreement** instance. 2617 2618For details about the supported specifications, see [Key Agreement Specifications](../../security/cryptoFramework-overview.md#key-agreement-specifications). 2619 2620**System capability**: SystemCapability.Security.CryptoFramework 2621 2622**Parameters** 2623 2624| Name | Type | Mandatory| Description | 2625| ------- | ------ | ---- | ------------------------------- | 2626| algName | string | Yes | Key agreement algorithm to use. Only ECC is supported.| 2627 2628**Return value** 2629 2630| Type | Description | 2631| ------------ | ---------------------------------------- | 2632| KeyAgreement | **KeyAgreement** instance created.| 2633 2634**Example** 2635 2636```javascript 2637import cryptoFramework from "@ohos.security.cryptoFramework" 2638 2639let keyAgreement = cryptoFramework.createKeyAgreement("ECC256"); 2640 2641``` 2642 2643## KeyAgreement 2644 2645Provides APIs for key agreement operations. Before using any API of the **KeyAgreement** class, you must create a **KeyAgreement** instance by using **createKeyAgreement()**. 2646 2647### Attributes 2648 2649**System capability**: SystemCapability.Security.CryptoFramework 2650 2651| Name | Type | Readable| Writable| Description | 2652| ------- | ------ | ---- | ---- | ---------------------------- | 2653| algName | string | Yes | No | Algorithm used for key agreement.| 2654 2655### generateSecret 2656 2657generateSecret(priKey : PriKey, pubKey : PubKey, callback : AsyncCallback\<DataBlob>) : void 2658 2659Generates a shared secret. This API uses an asynchronous callback to return the result. 2660 2661**System capability**: SystemCapability.Security.CryptoFramework 2662 2663**Parameters** 2664 2665| Name | Type | Mandatory| Description | 2666| -------- | ------------------------ | ---- | ---------------------- | 2667| priKey | [PriKey](#prikey) | Yes | Private key used for key agreement.| 2668| pubKey | [PubKey](#pubkey) | Yes | Public key used for key agreement.| 2669| callback | AsyncCallback\<[DataBlob](#datablob)> | Yes | Callback invoked to return the shared secret.| 2670 2671**Error codes** 2672 2673| ID| Error Message | 2674| -------- | ---------------------- | 2675| 17620001 | memory error. | 2676| 17620002 | runtime error. | 2677| 17630001 | crypto operation error. | 2678 2679### generateSecret 2680 2681generateSecret(priKey : PriKey, pubKey : PubKey) : Promise\<DataBlob> 2682 2683Generates a shared secret. This API uses a promise to return the result. 2684 2685**System capability**: SystemCapability.Security.CryptoFramework 2686 2687**Parameters** 2688 2689| Name| Type | Mandatory| Description | 2690| ------ | ------ | ---- | ---------------------- | 2691| priKey | [PriKey](#prikey) | Yes | Private key used for key agreement.| 2692| pubKey | [PubKey](#pubkey) | Yes | Public key used for key agreement.| 2693 2694**Return value** 2695 2696| Type | Description | 2697| ------------------ | -------- | 2698| Promise\<[DataBlob](#datablob)> | Promise used to return the shared secret.| 2699 2700**Error codes** 2701 2702| ID| Error Message | 2703| -------- | ---------------------- | 2704| 17620001 | memory error. | 2705| 17620002 | runtime error. | 2706| 17630001 | crypto operation error. | 2707 2708**Callback example**: 2709 2710```javascript 2711import cryptoFramework from "@ohos.security.cryptoFramework" 2712 2713let globalKeyPair; // globalKeyPair is an asymmetric key object generated by the asymmetric key generator. The generation process is omitted here. 2714let keyAgreement = cryptoFramework.createKeyAgreement("ECC256"); 2715keyAgreement.generateSecret(globalKeyPair.priKey, globalKeyPair.pubKey, function (err, secret) { 2716 if (err) { 2717 console.error("keyAgreement error."); 2718 return; 2719 } 2720 console.info("keyAgreement output is " + secret.data); 2721}); 2722``` 2723 2724**Promise example**: 2725 2726```javascript 2727import cryptoFramework from "@ohos.security.cryptoFramework" 2728 2729let globalKeyPair; // globalKeyPair is an asymmetric key object generated by the asymmetric key generator. The generation process is omitted here. 2730let keyAgreement = cryptoFramework.createKeyAgreement("ECC256"); 2731let keyAgreementPromise = keyAgreement.generateSecret(globalKeyPair.priKey, globalKeyPair.pubKey); 2732keyAgreementPromise.then((secret) => { 2733 console.info("keyAgreement output is " + secret.data); 2734}).catch((error) => { 2735 console.error("keyAgreement error."); 2736}); 2737``` 2738