1# @ohos.security.cryptoFramework (加解密算法库框架) 2 3为屏蔽底层硬件和算法库,向上提供统一的密码算法库加解密相关接口。 4 5> **说明:** 6> 7> - 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 8> - 以下示例代码片段仅适用于JS语言开发。 9 10## 导入模块 11 12```ts 13import cryptoFramework from "@ohos.security.cryptoFramework"; 14``` 15 16## Result 17 18 表示执行结果的枚举。 19 20 **系统能力:** SystemCapability.Security.CryptoFramework 21 22| 名称 | 值 | 说明 | 23| ------------------------------------- | -------- | ---------------------------- | 24| INVALID_PARAMS | 401 | 非法入参。 | 25| NOT_SUPPORT | 801 | 操作不支持。 | 26| ERR_OUT_OF_MEMORY | 17620001 | 内存错误。 | 27| ERR_RUNTIME_ERROR | 17620002 | 运行时外部错误。 | 28| ERR_CRYPTO_OPERATION | 17630001 | 调用三方算 法库API出错。 | 29 30## DataBlob 31 32buffer数组。 33 34 **系统能力:** SystemCapability.Security.CryptoFramework 35 36| 名称 | 类型 | 可读 | 可写 | 说明 | 37| ---- | ---------- | ---- | ---- | ------ | 38| data | Uint8Array | 是 | 是 | 数据。 | 39 40## ParamsSpec 41 42加解密参数,在进行对称加解密时需要构造其子类对象,并将子类对象传入[init()](#init-2)方法。 43 44适用于需要iv等参数的对称加解密模式(对于无iv等参数的模式如ECB模式,无需构造,在[init()](#init-2)中传入null即可)。 45 46**系统能力:** SystemCapability.Security.CryptoFramework 47 48| 名称 | 类型 | 可读 | 可写 | 说明 | 49| ------- | ------ | ---- | ---- | ------------------------------------------------------------ | 50| algName | string | 是 | 是 | 指明对称加解密参数的算法模式。可选值如下:<br/> - "IvParamsSpec": 适用于CBC\|CTR\|OFB\|CFB模式<br/> - "GcmParamsSpec": 适用于GCM模式<br/> - "CcmParamsSpec": 适用于CCM模式 | 51 52> **说明:** 53> 54> 由于[init()](#init-2)的params参数是ParamsSpec类型(父类),而实际需要传入具体的子类对象(如IvParamsSpec),因此在构造子类对象时应设置其父类ParamsSpec的algName参数,使算法库在init()时知道传入的是哪种子类对象。 55 56## IvParamsSpec 57 58加解密参数[ParamsSpec](#paramsspec)的子类,用于在对称加解密时作为[init()](#init-2)方法的参数。 59 60适用于CBC、CTR、OFB、CFB这些仅使用iv作为参数的加解密模式。 61 62**系统能力:** SystemCapability.Security.CryptoFramework 63 64| 名称 | 类型 | 可读 | 可写 | 说明 | 65| ---- | --------------------- | ---- | ---- | ------------------------------------------------------------ | 66| iv | [DataBlob](#datablob) | 是 | 是 | 指明加解密参数iv。常见取值如下:<br/>- AES的CBC\|CTR\|OFB\|CFB模式:iv长度为16字节<br/>- 3DES的CBC\|OFB\|CFB模式:iv长度为8字节<br/>- SM4<sup>10+</sup>的CBC\|CTR\|OFB\|CFB模式:iv长度为16字节。 | 67 68> **说明:** 69> 70> 传入[init()](#init-2)方法前需要指定其algName属性(来源于父类[ParamsSpec](#paramsspec))。 71 72## GcmParamsSpec 73 74加解密参数[ParamsSpec](#paramsspec)的子类,用于在对称加解密时作为[init()](#init-2)方法的参数。 75 76适用于GCM模式。 77 78**系统能力:** SystemCapability.Security.CryptoFramework 79 80| 名称 | 类型 | 可读 | 可写 | 说明 | 81| ------- | --------------------- | ---- | ---- | ------------------------------------------------------------ | 82| iv | [DataBlob](#datablob) | 是 | 是 | 指明加解密参数iv,长度为12字节。 | 83| aad | [DataBlob](#datablob) | 是 | 是 | 指明加解密参数aad,长度为8字节。 | 84| authTag | [DataBlob](#datablob) | 是 | 是 | 指明加解密参数authTag,长度为16字节。<br/>采用GCM模式加密时,需要获取[doFinal()](#dofinal-2)输出的[DataBlob](#datablob),取出其末尾16字节作为解密时[init()](#init-2)方法的入参[GcmParamsSpec](#gcmparamsspec)中的的authTag。 | 85 86> **说明:** 87> 88> 传入[init()](#init-2)方法前需要指定其algName属性(来源于父类[ParamsSpec](#paramsspec))。 89 90## CcmParamsSpec 91 92加解密参数[ParamsSpec](#paramsspec)的子类,用于在对称加解密时作为[init()](#init-2)方法的参数。 93 94适用于CCM模式。 95 96**系统能力:** SystemCapability.Security.CryptoFramework 97 98| 名称 | 类型 | 可读 | 可写 | 说明 | 99| ------- | --------------------- | ---- | ---- | ------------------------------------------------------------ | 100| iv | [DataBlob](#datablob) | 是 | 是 | 指明加解密参数iv,长度为7字节。 | 101| aad | [DataBlob](#datablob) | 是 | 是 | 指明加解密参数aad,长度为8字节。 | 102| authTag | [DataBlob](#datablob) | 是 | 是 | 指明加解密参数authTag,长度为12字节。<br/>采用CCM模式加密时,需要获取[doFinal()](#dofinal-2)输出的[DataBlob](#datablob),取出其末尾12字节作为解密时[init()](#init-2)方法的入参[CcmParamsSpec](#ccmparamsspec)中的authTag。 | 103 104> **说明:** 105> 106> 传入[init()](#init-2)方法前需要指定其algName属性(来源于父类[ParamsSpec](#paramsspec))。 107 108## CryptoMode 109 110表示加解密操作的枚举。 111 112**系统能力:** SystemCapability.Security.CryptoFramework 113 114| 名称 | 值 | 说明 | 115| ------------ | ---- | ------------------ | 116| ENCRYPT_MODE | 0 | 表示进行加密操作。 | 117| DECRYPT_MODE | 1 | 表示进行解密操作。 | 118 119## AsyKeySpecItem<sup>10+</sup> 120 121表示密钥参数的枚举。 122 123**系统能力:** SystemCapability.Security.CryptoFramework 124 125| 名称 | 值 | 说明 | 126| ------------ | ---- | ---------------- | 127| DSA_P_BN | 101 | DSA算法的素模数p。 | 128| DSA_Q_BN | 102 | DSA算法中密钥参数q(p-1的素因子)。 | 129| DSA_G_BN | 103 | DSA算法的参数g。 | 130| DSA_SK_BN | 104 | DSA算法的私钥sk。 | 131| DSA_PK_BN | 105 | DSA算法的公钥pk。 | 132| ECC_FP_P_BN | 201 | DSA算法中表示椭圆曲线Fp域的素数p。 | 133| ECC_A_BN | 202 | DSA算法中椭圆曲线的第一个系数a。 | 134| ECC_B_BN | 203 | DSA算法中椭圆曲线的第二个系数b。 | 135| ECC_G_X_BN | 204 | ECC算法中基点g的x坐标。 | 136| ECC_G_Y_BN | 205 | ECC算法中基点g的y坐标。 | 137| ECC_N_BN | 206 | ECC算法中基点g的阶n。 | 138| ECC_H_NUM | 207 | ECC算法中的余因子h。 | 139| ECC_SK_BN | 208 | ECC算法中的私钥sk。 | 140| ECC_PK_X_BN | 209 | ECC算法中,公钥pk(椭圆曲线上的一个点)的x坐标。 | 141| ECC_PK_Y_BN | 210 | ECC算法中,公钥pk(椭圆曲线上的一个点)的y坐标。 | 142| ECC_FIELD_TYPE_STR | 211 | ECC算法中,椭圆曲线的域类型(当前只支持Fp域)。 | 143| ECC_FIELD_SIZE_NUM | 212 | ECC算法中域的大小,单位为bits(注:对于Fp域,域的大小为素数p的bits长度)。 | 144| ECC_CURVE_NAME_STR | 213 | ECC算法中的SECG曲线名称。 | 145| RSA_N_BN | 301 | RSA算法中的模数n。 | 146| RSA_SK_BN | 302 | RSA算法中的私钥sk(即私钥指数d)。 | 147| RSA_PK_BN | 303 | RSA算法中的公钥pk(即公钥指数e)。 | 148 149## AsyKeySpecType<sup>10+</sup> 150 151表示密钥参数类型的枚举。 152 153**系统能力:** SystemCapability.Security.CryptoFramework 154 155| 名称 | 值 | 说明 | 156| ------------ | ---- | ---------------- | 157| COMMON_PARAMS_SPEC | 0 | 表示公私钥中包含的公共参数。使用此类型的参数可以调用[generateKeyPair](#generatekeypair-2)随机生成密钥对。 | 158| PRIVATE_KEY_SPEC | 1 | 表示私钥中包含的参数。使用此类型的参数可以调用[generatePriKey](#generateprikey)生成指定的私钥。 | 159| PUBLIC_KEY_SPEC | 2 | 表示公钥中包含的参数。使用此类型的参数可以调用[generatePubKey](#generatepubkey)生成指定的公钥。 | 160| KEY_PAIR_SPEC | 3 | 表示公私钥中包含的全量参数。使用此类型的参数可以调用[generateKeyPair](#generatekeypair-2)生成指定的密钥对。 | 161 162## CipherSpecItem<sup>10+</sup> 163 164表示加解密参数的枚举,这些加解密参数支持通过[setCipherSpec](#setcipherspec10)接口设置/通过[getCipherSpec](#getcipherspec10)接口获取。 165 166当前只支持RSA算法,详细规格请参考框架概述[加解密规格](../../security/cryptoFramework-overview.md#加解密规格) 167 168**系统能力:** SystemCapability.Security.CryptoFramework 169 170| 名称 | 值 | 说明 | 171| ------------ | ---- | ---------------- | 172| OAEP_MD_NAME_STR | 100 | 表示RSA算法中,使用PKCS1_OAEP模式时,消息摘要功能的算法名。 | 173| OAEP_MGF_NAME_STR | 101 | 表示RSA算法中,使用PKCS1_OAEP模式时,掩码生成算法(目前仅支持MGF1)。 | 174| OAEP_MGF1_MD_STR | 102 | 表示RSA算法中,使用PKCS1_OAEP模式时,MGF1掩码生成功能的消息摘要算法。 | 175| OAEP_MGF1_PSRC_UINT8ARR | 103 | 表示RSA算法中,使用PKCS1_OAEP模式时,pSource的字节流。 | 176 177## SignSpecItem<sup>10+</sup> 178 179表示签名验签参数的枚举,这些签名验签参数支持通过[setSignSpec](#setsignspec10)、[setVerifySpec](#setverifyspec10)接口设置/通过[getSignSpec](#getsignspec10)、[getVerifySpec](#getverifyspec10)接口获取。 180 181当前只支持RSA算法,详细规格请参考框架概述[加解密规格](../../security/cryptoFramework-overview.md#加解密规格) 182 183**系统能力:** SystemCapability.Security.CryptoFramework 184 185| 名称 | 值 | 说明 | 186| ------------ | ---- | ---------------- | 187| PSS_MD_NAME_STR | 100 | 表示RSA算法中,使用PSS模式时,消息摘要功能的算法名。 | 188| PSS_MGF_NAME_STR | 101 | 表示RSA算法中,使用PSS模式时,掩码生成算法(目前仅支持MGF1)。 | 189| PSS_MGF1_MD_STR | 102 | 表示RSA算法中,使用PSS模式时,MGF1掩码生成功能的消息摘要参数。 | 190| PSS_SALT_LEN_NUM | 103 | 表示RSA算法中,使用PSS模式时,盐值的长度,长度以字节为单位。 | 191| PSS_TRAILER_FIELD_NUM | 104 | 表示RSA算法中,使用PSS模式时,用于编码操作的整数,值为1。 | 192 193## AsyKeySpec<sup>10+</sup> 194 195指定非对称密钥参数的基本接口,用于创建密钥生成器。在指定非对称密钥参数时需要构造其子类对象,并将子类对象传入[createAsyKeyGeneratorBySpec()](#cryptoframeworkcreateasykeygeneratorbyspec10)方法创建密钥生成器。构造子类对象时,所有bigint类型的密钥参数均采用大端写法,并使用正数。 196 197**系统能力:** SystemCapability.Security.CryptoFramework 198 199| 名称 | 类型 | 可读 | 可写 | 说明 | 200| ------- | ------ | ---- | ---- | ------------------------------------------------------------ | 201| algName | string | 是 | 是 | 指定非对称密钥的算法名称,比如"RSA"、"DSA"、"ECC"。 | 202| specType | [AsyKeySpecType](#asykeyspectype10) | 是 | 是 | 指定密钥参数类型,用于区分公/私钥参数。 | 203 204## DSACommonParamsSpec<sup>10+</sup> 205 206密钥参数[AsyKeySpec](#asykeyspec10)的子类,用于指定DSA算法中公私钥包含的公共参数,随机生成公/私钥。 207 208在使用密钥参数生成密钥时,将其传入[createAsyKeyGeneratorBySpec()](#cryptoframeworkcreateasykeygeneratorbyspec10)方法创建密钥生成器。 209 210**系统能力:** SystemCapability.Security.CryptoFramework 211 212| 名称 | 类型 | 可读 | 可写 | 说明 | 213| ------- | ------ | ---- | ---- | ------------------------------------------------------------ | 214| p | bigint | 是 | 是 | 指定DSA算法的素模数p。 | 215| q | bigint | 是 | 是 | 指定DSA算法中密钥参数q(p-1的素因子)。 | 216| g | bigint | 是 | 是 | 指定DSA算法的参数g。 | 217 218## DSAPubKeySpec<sup>10+</sup> 219 220密钥参数[AsyKeySpec](#asykeyspec10)的子类,用于指定DSA算法中公钥包含的参数。 221 222在使用密钥参数生成密钥时,将其传入[createAsyKeyGeneratorBySpec()](#cryptoframeworkcreateasykeygeneratorbyspec10)方法创建密钥生成器。 223 224**系统能力:** SystemCapability.Security.CryptoFramework 225 226| 名称 | 类型 | 可读 | 可写 | 说明 | 227| ------- | ------ | ---- | ---- | ------------------------------------------------------------ | 228| params | [DSACommonParamsSpec](#dsacommonparamsspec10) | 是 | 是 | 指定DSA算法中公私钥都包含的公共参数。 | 229| pk | bigint | 是 | 是 | 指定DSA算法的公钥。 | 230 231## DSAKeyPairSpec<sup>10+</sup> 232 233密钥参数[AsyKeySpec](#asykeyspec10)的子类,用于指定DSA算法中公私钥包含的全量参数。 234 235在使用密钥参数生成密钥时,将其传入[createAsyKeyGeneratorBySpec()](#cryptoframeworkcreateasykeygeneratorbyspec10)方法创建密钥生成器。 236 237**系统能力:** SystemCapability.Security.CryptoFramework 238 239| 名称 | 类型 | 可读 | 可写 | 说明 | 240| ------- | ------ | ---- | ---- | ------------------------------------------------------------ | 241| params | [DSACommonParamsSpec](#dsacommonparamsspec10) | 是 | 是 | 指定DSA算法中公私钥都包含的公共参数。 | 242| sk | bigint | 是 | 是 | 指定DSA算法的私钥sk。 | 243| pk | bigint | 是 | 是 | 指定DSA算法的公钥pk。 | 244 245## ECField<sup>10+</sup> 246 247指定椭圆曲线的域。当前只支持Fp域。 248 249**系统能力:** SystemCapability.Security.CryptoFramework 250 251| 名称 | 类型 | 可读 | 可写 | 说明 | 252| ------- | ------ | ---- | ---- | ------------------------------------------------------------ | 253| fieldType | string | 是 | 是 | 指定椭圆曲线域的类型,当前只支持"Fp"。 | 254 255## ECFieldFp<sup>10+</sup> 256 257指定椭圆曲线素数域。是[ECField](#ecfield10)的子类。 258 259**系统能力:** SystemCapability.Security.CryptoFramework 260 261| 名称 | 类型 | 可读 | 可写 | 说明 | 262| ------- | ------ | ---- | ---- | ------------------------------------------------------------ | 263| p | bigint | 是 | 是 | 指定素数p。 | 264 265## Point<sup>10+</sup> 266 267指定椭圆曲线上的一个点。 268 269**系统能力:** SystemCapability.Security.CryptoFramework 270 271| 名称 | 类型 | 可读 | 可写 | 说明 | 272| ------- | ------ | ---- | ---- | ------------------------------------------------------------ | 273| x | bigint | 是 | 是 | 指定椭圆曲线上,点的x坐标。 | 274| y | bigint | 是 | 是 | 指定椭圆曲线上,点的y坐标。 | 275 276## ECCCommonParamsSpec<sup>10+</sup> 277 278密钥参数[AsyKeySpec](#asykeyspec10)的子类,用于指定ECC算法中公私钥包含的公共参数,随机生成公/私钥。 279 280在使用密钥参数生成密钥时,将其传入[createAsyKeyGeneratorBySpec()](#cryptoframeworkcreateasykeygeneratorbyspec10)方法创建密钥生成器。 281 282**系统能力:** SystemCapability.Security.CryptoFramework 283 284| 名称 | 类型 | 可读 | 可写 | 说明 | 285| ------- | ------ | ---- | ---- | ------------------------------------------------------------ | 286| field | [ECField](#ecfield10) | 是 | 是 | 指定椭圆曲线的域(当前只支持Fp域)。 | 287| a | bigint | 是 | 是 | 指定椭圆曲线的第一个系数a。 | 288| b | bigint | 是 | 是 | 指定椭圆曲线的第二个系数b。 | 289| g | [Point](#point10) | 是 | 是 | 指定基点g。 | 290| n | bigint | 是 | 是 | 指定基点g的阶数n。 | 291| h | number | 是 | 是 | 指定余因子h。 | 292 293## ECCPriKeySpec<sup>10+</sup> 294 295密钥参数[AsyKeySpec](#asykeyspec10)的子类,用于指定ECC算法中私钥包含的参数。 296 297在使用密钥参数生成密钥时,将其传入[createAsyKeyGeneratorBySpec()](#cryptoframeworkcreateasykeygeneratorbyspec10)方法创建密钥生成器。 298 299**系统能力:** SystemCapability.Security.CryptoFramework 300 301| 名称 | 类型 | 可读 | 可写 | 说明 | 302| ------- | ------ | ---- | ---- | ------------------------------------------------------------ | 303| params | [ECCCommonParamsSpec](#ecccommonparamsspec10) | 是 | 是 | 指定ECC算法中公私钥都包含的公共参数。 | 304| sk | bigint | 是 | 是 | 指定ECC算法的私钥sk。 | 305 306## ECCPubKeySpec<sup>10+</sup> 307 308密钥参数[AsyKeySpec](#asykeyspec10)的子类,用于指定ECC算法中公钥包含的参数。 309 310在使用密钥参数生成密钥时,将其传入[createAsyKeyGeneratorBySpec()](#cryptoframeworkcreateasykeygeneratorbyspec10)方法创建密钥生成器。 311 312**系统能力:** SystemCapability.Security.CryptoFramework 313 314| 名称 | 类型 | 可读 | 可写 | 说明 | 315| ------- | ------ | ---- | ---- | ------------------------------------------------------------ | 316| params | [ECCCommonParamsSpec](#ecccommonparamsspec10) | 是 | 是 | 指定ECC算法中公私钥都包含的公共参数。 | 317| pk | [Point](#point10) | 是 | 是 | 指定ECC算法的公钥pk。 | 318 319## ECCKeyPairSpec<sup>10+</sup> 320 321密钥参数[AsyKeySpec](#asykeyspec10)的子类,用于指定ECC算法中公私钥包含的全量参数。 322 323在使用密钥参数生成密钥时,将其传入[createAsyKeyGeneratorBySpec()](#cryptoframeworkcreateasykeygeneratorbyspec10)方法创建密钥生成器。 324 325**系统能力:** SystemCapability.Security.CryptoFramework 326 327| 名称 | 类型 | 可读 | 可写 | 说明 | 328| ------- | ------ | ---- | ---- | ------------------------------------------------------------ | 329| params | [ECCCommonParamsSpec](#ecccommonparamsspec10) | 是 | 是 | 指定ECC算法中公私钥都包含的公共参数。 | 330| sk | bigint | 是 | 是 | 指定ECC算法的私钥sk。 | 331| pk | [Point](#point10) | 是 | 是 | 指定ECC算法的公钥pk。 | 332 333## RSACommonParamsSpec<sup>10+</sup> 334 335密钥参数[AsyKeySpec](#asykeyspec10)的子类,用于指定RSA算法中公私钥包含的公共参数,随机生成公/私钥。 336 337在使用密钥参数生成密钥时,将其传入[createAsyKeyGeneratorBySpec()](#cryptoframeworkcreateasykeygeneratorbyspec10)方法创建密钥生成器。 338 339**系统能力:** SystemCapability.Security.CryptoFramework 340 341| 名称 | 类型 | 可读 | 可写 | 说明 | 342| ------- | ------ | ---- | ---- | ------------------------------------------------------------ | 343| n | bigint | 是 | 是 | 指定模数n。 | 344 345## RSAPubKeySpec<sup>10+</sup> 346 347密钥参数[AsyKeySpec](#asykeyspec10)的子类,用于指定RSA算法中公钥包含的参数。 348 349在使用密钥参数生成密钥时,将其传入[createAsyKeyGeneratorBySpec()](#cryptoframeworkcreateasykeygeneratorbyspec10)方法创建密钥生成器。 350 351**系统能力:** SystemCapability.Security.CryptoFramework 352 353| 名称 | 类型 | 可读 | 可写 | 说明 | 354| ------- | ------ | ---- | ---- | ------------------------------------------------------------ | 355| params | [RSACommonParamsSpec](#rsacommonparamsspec10) | 是 | 是 | 指定RSA算法中公私钥都包含的公共参数。 | 356| pk | bigint | 是 | 是 | 指定RSA算法的公钥pk。 | 357 358## RSAKeyPairSpec<sup>10+</sup> 359 360密钥参数[AsyKeySpec](#asykeyspec10)的子类,用于指定RSA算法中公私钥包含的全量参数。 361 362在使用密钥参数生成密钥时,将其传入[createAsyKeyGeneratorBySpec()](#cryptoframeworkcreateasykeygeneratorbyspec10)方法创建密钥生成器。 363 364**系统能力:** SystemCapability.Security.CryptoFramework 365 366| 名称 | 类型 | 可读 | 可写 | 说明 | 367| ------- | ------ | ---- | ---- | ------------------------------------------------------------ | 368| params | [RSACommonParamsSpec](#rsacommonparamsspec10) | 是 | 是 | 指定RSA算法中公私钥都包含的公共参数。 | 369| sk | bigint | 是 | 是 | 指定RSA算法的私钥sk。 | 370| pk | bigint | 是 | 是 | 指定RSA算法的公钥pk。 | 371 372## Key 373 374密钥(父类),在运行密码算法(如加解密)时需要提前生成其子类对象,并传入[Cipher](#cipher)实例的[init()](#init-2)方法。 375 376密钥可以通过密钥生成器来生成。 377 378### 属性 379 380**系统能力:** SystemCapability.Security.CryptoFramework 381 382| 名称 | 类型 | 可读 | 可写 | 说明 | 383| ------- | ------ | ---- | ---- | ---------------------------- | 384| format | string | 是 | 否 | 密钥的格式。 | 385| algName | string | 是 | 否 | 密钥对应的算法名(含长度)。 | 386 387### getEncoded 388 389getEncoded(): DataBlob 390 391同步方法,获取密钥数据的字节流。密钥可以为对称密钥,公钥或者私钥。其中,公钥格式满足ASN.1语法、X.509规范、DER编码格式;私钥格式满足ASN.1语法,PKCS#8规范、DER编码方式。 392 393> **说明:** 394> 395> RSA算法使用密钥参数生成私钥时,私钥对象不支持getEncoded。 396 397**系统能力:** SystemCapability.Security.CryptoFramework 398 399**返回值:** 400 401| 类型 | 说明 | 402| --------------------- | ------------------------ | 403| [DataBlob](#datablob) | 用于查看密钥的具体内容。 | 404 405**错误码:** 406 407| 错误码ID | 错误信息 | 408| -------- | ---------------------- | 409| 801 | this operation is not supported. | 410| 17620001 | memory error. | 411| 17630001 | crypto operation error. | 412 413**示例:** 414 415```ts 416let key: cryptoFramework.SymKey; // The key is generated by a key generator. The generation process is omitted here. 417let encodedKey = key.getEncoded(); 418console.info("key blob:" + encodedKey.data); 419``` 420 421## SymKey 422 423对称密钥,是[Key](#key)的子类,在对称加解密时需要将其对象传入[Cipher](#cipher)实例的[init()](#init-2)方法使用。 424 425对称密钥可以通过对称密钥生成器[SymKeyGenerator](#symkeygenerator)来生成。 426 427### clearMem 428 429clearMem(): void 430 431同步方法,将系统底层内存中的的密钥内容清零。建议在不再使用对称密钥实例时,调用本函数,避免内存中密钥数据存留过久。 432 433**系统能力:** SystemCapability.Security.CryptoFramework 434 435**示例:** 436 437```ts 438let key: cryptoFramework.SymKey; // The key is generated by a symKeyGenerator. The generation process is omitted here. 439let encodedKey = key.getEncoded(); 440console.info("key blob: "+ encodedKey.data); // Display key content. 441key.clearMem(); 442encodedKey = key.getEncoded(); 443console.info("key blob:" + encodedKey.data); // Display all 0s. 444``` 445 446## PubKey 447 448公钥,是Key的子类,在非对称加解密、验签、密钥协商时需要将其对象作为输入使用。 449 450公钥可以通过非对称密钥生成器[AsyKeyGenerator](#asykeygenerator)、[AsyKeyGeneratorBySpec](#asykeygeneratorbyspec10)来生成。 451 452### 属性 453 454**系统能力:** SystemCapability.Security.CryptoFramework 455 456| 名称 | 类型 | 可读 | 可写 | 说明 | 457| ------- | ------ | ---- | ---- | ---------------------------- | 458| format | string | 是 | 否 | 密钥的格式。 | 459| algName | string | 是 | 否 | 密钥对应的算法名(含长度)。 | 460 461### getAsyKeySpec<sup>10+</sup> 462 463getAsyKeySpec(itemType: AsyKeySpecItem): bigint | string | number 464 465同步方法,获取密钥参数。 466 467**系统能力:** SystemCapability.Security.CryptoFramework 468 469**参数:** 470 471| 参数名 | 类型 | 必填 | 说明 | 472| ---- | --------------------- | ---- | -------------------- | 473| item | [AsyKeySpecItem](#asykeyspecitem10) | 是 | 指定的密钥参数。 | 474 475**返回值:** 476 477| 类型 | 说明 | 478| --------------------------- | --------------------------------- | 479| bigint\|string\|number | 用于查看密钥参数的具体内容。 | 480 481**错误码:** 482 483| 错误码ID | 错误信息 | 484| -------- | ---------------------- | 485| 401 | invalid parameters. | 486| 17620001 | memory error. | 487| 17630001 | crypto operation error. | 488 489**示例:** 490 491```ts 492let key: cryptoFramework.PubKey; // key is a public key object. The generation process is omitted here. 493let p = key.getAsyKeySpec(cryptoFramework.AsyKeySpecItem.ECC_FP_P_BN); 494console.info("ecc item --- p: " + p.toString(16)); 495``` 496 497## PriKey 498 499私钥,是Key的子类,在非对称加解密、签名、密钥协商时需要将其作为输入使用。 500 501私钥可以通过非对称密钥生成器[AsyKeyGenerator](#asykeygenerator)、[AsyKeyGeneratorBySpec](#asykeygeneratorbyspec10)来生成。 502 503### 属性 504 505**系统能力:** SystemCapability.Security.CryptoFramework 506 507| 名称 | 类型 | 可读 | 可写 | 说明 | 508| ------- | ------ | ---- | ---- | ---------------------------- | 509| format | string | 是 | 否 | 密钥的格式。 | 510| algName | string | 是 | 否 | 密钥对应的算法名(含长度)。 | 511 512### clearMem 513 514clearMem(): void 515 516同步方法,将系统底层内存中的的密钥内容清零。 517 518**系统能力:** SystemCapability.Security.CryptoFramework 519 520**示例:** 521 522```ts 523let key: cryptoFramework.PriKey; // The key is a private key generated by the asymmetric key generator. The generation process is omitted here. 524key.clearMem(); // For the asymmetric private key, clearMem() releases the internal key struct. After clearMem is executed, getEncoded() is not supported. } 525``` 526 527### getAsyKeySpec<sup>10+</sup> 528 529getAsyKeySpec(itemType: AsyKeySpecItem): bigint | string | number 530 531同步方法,获取密钥参数。 532 533**系统能力:** SystemCapability.Security.CryptoFramework 534 535**参数:** 536 537| 参数名 | 类型 | 必填 | 说明 | 538| ---- | --------------------- | ---- | -------------------- | 539| item | [AsyKeySpecItem](#asykeyspecitem10) | 是 | 指定的密钥参数类型。 | 540 541**返回值:** 542 543| 类型 | 说明 | 544| --------------------------- | --------------------------------- | 545| bigint\|string\|number | 用于查看密钥参数的具体内容。 | 546 547**错误码:** 548 549| 错误码ID | 错误信息 | 550| -------- | ---------------------- | 551| 401 | invalid parameters. | 552| 17620001 | memory error. | 553| 17630001 | crypto operation error. | 554 555**示例:** 556 557```ts 558let key: cryptoFramework.PriKey; // key is a private key object. The generation process is omitted here. 559let p = key.getAsyKeySpec(cryptoFramework.AsyKeySpecItem.ECC_FP_P_BN); 560console.info("ecc item --- p: " + p.toString(16)); 561``` 562 563## KeyPair 564 565非对称密钥对,包含:公钥与私钥。 566 567可以通过非对称密钥生成器[AsyKeyGenerator](#asykeygenerator)、[AsyKeyGeneratorBySpec](#asykeygeneratorbyspec10)来生成。 568 569> **说明:** 570> 571> KeyPair对象中的pubKey对象和priKey对象,作为KeyPair对象中的一个参数存在,当离开KeyPair对象作用域时,其内部对象可能被析构。 572> 573> 业务方使用时应持有KeyPair对象的引用,而非内部pubKey或priKey对象的引用。 574 575### 属性 576 577**系统能力:** SystemCapability.Security.CryptoFramework 578 579| 名称 | 类型 | 可读 | 可写 | 说明 | 580| ------- | ------ | ---- | ---- | ------------ | 581| priKey | [PriKey](#prikey) | 是 | 否 | 私钥。 | 582| pubKey | [PubKey](#pubkey) | 是 | 否 | 公钥。 | 583 584## cryptoFramework.createSymKeyGenerator 585 586createSymKeyGenerator(algName: string): SymKeyGenerator 587 588通过指定算法名称的字符串,获取相应的对称密钥生成器实例。 589 590支持的规格详见框架概述“[密钥生成规格](../../security/cryptoFramework-overview.md#密钥生成规格)”一节。 591 592**系统能力:** SystemCapability.Security.CryptoFramework 593 594**参数:** 595 596| 参数名 | 类型 | 必填 | 说明 | 597| ------- | ------ | ---- | ------------------------------------------------------------ | 598| algName | string | 是 | 待生成对称密钥生成器的算法名称。<br/>具体取值详见框架概述“[密钥生成规格](../../security/cryptoFramework-overview.md#密钥生成规格)”一节中的“字符串参数”。 | 599 600**返回值:** 601 602| 类型 | 说明 | 603| ----------------------------------- | -------------------------- | 604| [SymKeyGenerator](#symkeygenerator) | 返回对称密钥生成器的对象。 | 605 606| 错误码ID | 错误信息 | 607| -------- | ---------------------- | 608| 401 | invalid parameters. | 609| 801 | this operation is not supported. | 610 611**示例:** 612 613```ts 614let symKeyGenerator = cryptoFramework.createSymKeyGenerator('3DES192'); 615``` 616 617## SymKeyGenerator 618 619对称密钥生成器。 620 621在使用该类的方法前,需要先使用[createSymKeyGenerator](#cryptoframeworkcreatesymkeygenerator)方法构建一个symKeyGenerator实例。 622 623### 属性 624 625**系统能力:** SystemCapability.Security.CryptoFramework 626 627| 名称 | 类型 | 可读 | 可写 | 说明 | 628| ------- | ------ | ---- | ---- | ------------------------------ | 629| algName | string | 是 | 否 | 对称密钥生成器指定的算法名称。 | 630 631### generateSymKey 632 633generateSymKey(callback: AsyncCallback\<SymKey>): void 634 635异步获取对称密钥生成器随机生成的密钥,通过注册回调函数获取结果。 636 637必须在使用[createSymKeyGenerator](#cryptoframeworkcreatesymkeygenerator)创建对称密钥生成器后,才能使用本函数。 638 639目前支持使用OpenSSL的RAND_priv_bytes()作为底层能力生成随机密钥。 640 641**系统能力:** SystemCapability.Security.CryptoFramework 642 643**参数:** 644 645| 参数名 | 类型 | 必填 | 说明 | 646| -------- | --------------------------------- | ---- | ------------------------------------------------------------ | 647| callback | AsyncCallback\<[SymKey](#symkey)> | 是 | 回调函数。当生成对称密钥成功,err为undefined,data为获取到的SymKey;否则为错误对象。 | 648 649**错误码:** 650 651| 错误码ID | 错误信息 | 652| -------- | ------------- | 653| 17620001 | memory error. | 654 655**示例:** 656 657```ts 658import { BusinessError } from '@ohos.base'; 659 660let symAlgName = '3DES192'; 661let symKeyGenerator = cryptoFramework.createSymKeyGenerator(symAlgName); 662symKeyGenerator.generateSymKey((err, symKey) => { 663 if (err) { 664 console.error(`Generate symKey failed, ${err.code}, ${err.message}`); 665 } else { 666 console.info(`Generate symKey success, algName: ${symKey.algName}`); 667 } 668}) 669``` 670 671### generateSymKey 672 673generateSymKey(): Promise\<SymKey> 674 675异步获取该对称密钥生成器随机生成的密钥,通过Promise获取结果。 676 677必须在使用[createSymKeyGenerator](#cryptoframeworkcreatesymkeygenerator)创建对称密钥生成器后,才能使用本函数。 678 679目前支持使用OpenSSL的RAND_priv_bytes()作为底层能力生成随机密钥。 680 681**系统能力:** SystemCapability.Security.CryptoFramework 682 683**返回值:** 684 685| 类型 | 说明 | 686| --------------------------- | --------------------------------- | 687| Promise\<[SymKey](#symkey)> | Promise对象,返回对称密钥SymKey。 | 688 689**错误码:** 690 691| 错误码ID | 错误信息 | 692| -------- | ------------- | 693| 17620001 | memory error. | 694 695**示例:** 696 697```ts 698import { BusinessError } from '@ohos.base'; 699 700let symAlgName = 'AES128'; 701let symKeyGenerator = cryptoFramework.createSymKeyGenerator(symAlgName); 702symKeyGenerator.generateSymKey() 703 .then(symKey => { 704 console.info(`Generate symKey success, algName: ${symKey.algName}`); 705 }, (error: BusinessError) => { 706 console.error(`Generate symKey failed, ${error.code}, ${error.message}`); 707 }) 708``` 709 710### convertKey 711 712convertKey(key: DataBlob, callback: AsyncCallback\<SymKey>): void 713 714异步根据指定数据生成对称密钥,通过注册回调函数获取结果。 715 716必须在使用[createSymKeyGenerator](#cryptoframeworkcreatesymkeygenerator)创建对称密钥生成器后,才能使用本函数。 717 718**系统能力:** SystemCapability.Security.CryptoFramework 719 720**参数:** 721 722| 参数名 | 类型 | 必填 | 说明 | 723| -------- | ------------------- | ---- | ---------------------| 724| key | [DataBlob](#datablob) | 是 | 指定的对称密钥材料。 | 725| callback | AsyncCallback\<[SymKey](#symkey)> | 是 | 回调函数。当生成对称密钥成功,err为undefined,data为获取到的SymKey;否则为错误对象。 | 726 727**错误码:** 728 729| 错误码ID | 错误信息 | 730| -------- | --------------------------------------------------- | 731| 401 | invalid parameters. | 732| 17620001 | memory error. | 733 734**示例:** 735 736```ts 737import { BusinessError } from '@ohos.base'; 738 739function genKeyMaterialBlob(): cryptoFramework.DataBlob { 740 let arr = [ 741 0xba, 0x3d, 0xc2, 0x71, 0x21, 0x1e, 0x30, 0x56, 742 0xad, 0x47, 0xfc, 0x5a, 0x46, 0x39, 0xee, 0x7c, 743 0xba, 0x3b, 0xc2, 0x71, 0xab, 0xa0, 0x30, 0x72]; // keyLen = 192 (24 bytes) 744 let keyMaterial = new Uint8Array(arr); 745 return { data: keyMaterial }; 746} 747 748let symAlgName = '3DES192'; 749let symKeyGenerator = cryptoFramework.createSymKeyGenerator(symAlgName); 750let keyMaterialBlob = genKeyMaterialBlob(); 751symKeyGenerator.convertKey(keyMaterialBlob, (err, symKey) => { 752 if (err) { 753 console.error(`Convert symKey failed, ${err.code}, ${err.message}`); 754 } else { 755 console.info(`Convert symKey success, algName: ${symKey.algName}`); 756 } 757}) 758``` 759 760### convertKey 761 762convertKey(key: DataBlob): Promise\<SymKey> 763 764异步根据指定数据生成对称密钥,通过Promise获取结果。 765 766必须在使用[createSymKeyGenerator](#cryptoframeworkcreatesymkeygenerator)创建对称密钥生成器后,才能使用本函数。 767 768**系统能力:** SystemCapability.Security.CryptoFramework 769 770**参数:** 771 772| 参数名 | 类型 | 必填 | 说明 | 773| ---- | --------------------- | ---- | -------------------- | 774| key | [DataBlob](#datablob) | 是 | 指定的密钥材料数据。 | 775 776**返回值:** 777 778| 类型 | 说明 | 779| --------------------------- | --------------------------------- | 780| Promise\<[SymKey](#symkey)> | Promise对象,返回对称密钥SymKey。 | 781 782**错误码:** 783 784| 错误码ID | 错误信息 | 785| -------- | --------------------------------------------- | 786| 401 | invalid parameters. | 787| 17620001 | memory error. | 788 789**示例:** 790 791```ts 792import { BusinessError } from '@ohos.base'; 793 794function genKeyMaterialBlob(): cryptoFramework.DataBlob { 795 let arr = [ 796 0xba, 0x3d, 0xc2, 0x71, 0x21, 0x1e, 0x30, 0x56, 797 0xad, 0x47, 0xfc, 0x5a, 0x46, 0x39, 0xee, 0x7c, 798 0xba, 0x3b, 0xc2, 0x71, 0xab, 0xa0, 0x30, 0x72]; // keyLen = 192 (24 bytes) 799 let keyMaterial = new Uint8Array(arr); 800 return { data: keyMaterial }; 801} 802 803let symAlgName = '3DES192'; 804let symKeyGenerator = cryptoFramework.createSymKeyGenerator(symAlgName); 805let keyMaterialBlob = genKeyMaterialBlob(); 806symKeyGenerator.convertKey(keyMaterialBlob) 807 .then(symKey => { 808 console.info(`Convert symKey success, algName: ${symKey.algName}`); 809 }, (error: BusinessError) => { 810 console.error(`Convert symKey failed, ${error.code}, ${error.message}`); 811 }) 812``` 813 814## cryptoFramework.createAsyKeyGenerator 815 816createAsyKeyGenerator(algName: string): AsyKeyGenerator 817 818通过指定算法名称的字符串,获取相应的非对称密钥生成器实例。 819 820支持的规格详见框架概述“[密钥生成规格](../../security/cryptoFramework-overview.md#密钥生成规格)”一节。 821 822**系统能力:** SystemCapability.Security.CryptoFramework 823 824**参数:** 825 826| 参数名 | 类型 | 必填 | 说明 | 827| ------- | ------ | ---- | -------------------------------- | 828| algName | string | 是 | 待生成对称密钥生成器的算法名称。 | 829 830**返回值:** 831 832| 类型 | 说明 | 833| --------------- | ---------------------------- | 834| [AsyKeyGenerator](#asykeygenerator) | 返回非对称密钥生成器的对象。 | 835 836**错误码:** 837 838| 错误码ID | 错误信息 | 839| -------- | ---------------------- | 840| 401 | invalid parameters. | 841| 801 | this operation is not supported. | 842| 17620001 | memory error. | 843 844**示例:** 845 846```ts 847let asyKeyGenerator = cryptoFramework.createAsyKeyGenerator("ECC256"); 848``` 849 850## AsyKeyGenerator 851 852非对称密钥生成器。在使用该类的方法前,需要先使用createAsyKeyGenerator()方法构建一个AsyKeyGenerator实例。 853 854### 属性 855 856**系统能力:** SystemCapability.Security.CryptoFramework 857 858| 名称 | 类型 | 可读 | 可写 | 说明 | 859| ------- | ------ | ---- | ---- | -------------------------------- | 860| algName | string | 是 | 否 | 非对称密钥生成器指定的算法名称。 | 861 862### generateKeyPair 863 864generateKeyPair(callback: AsyncCallback\<KeyPair>): void 865 866异步获取非对称密钥生成器随机生成的密钥,通过注册回调函数获取结果。 867 868**系统能力:** SystemCapability.Security.CryptoFramework 869 870**参数:** 871 872| 参数名 | 类型 | 必填 | 说明 | 873| -------- | ----------------------- | ---- | ------------------------------ | 874| callback | AsyncCallback\<[KeyPair](#keypair)> | 是 | 回调函数,用于获取非对称密钥。 | 875 876**错误码:** 877 878| 错误码ID | 错误信息 | 879| -------- | ---------------------- | 880| 401 | invalid parameters. | 881| 17620001 | memory error. | 882| 17630001 | crypto operation error. | 883 884**示例:** 885 886```ts 887import { BusinessError } from '@ohos.base'; 888 889let asyKeyGenerator = cryptoFramework.createAsyKeyGenerator("ECC256"); 890asyKeyGenerator.generateKeyPair((err, keyPair) => { 891 if (err) { 892 console.error("generateKeyPair: error."); 893 return; 894 } 895 console.info("generateKeyPair: success."); 896}) 897``` 898 899### generateKeyPair 900 901generateKeyPair(): Promise\<KeyPair> 902 903异步获取该非对称密钥生成器随机生成的密钥,通过Promise获取结果。 904 905**系统能力:** SystemCapability.Security.CryptoFramework 906 907**返回值:** 908 909| 类型 | 说明 | 910| ----------------- | --------------------------------- | 911| Promise\<[KeyPair](#keypair)> | 使用Promise的方式获取非对称密钥。 | 912 913**错误码:** 914 915| 错误码ID | 错误信息 | 916| -------- | ---------------------- | 917| 401 | invalid parameters. | 918| 17620001 | memory error. | 919| 17630001 | crypto operation error. | 920 921**示例:** 922 923```ts 924import { BusinessError } from '@ohos.base'; 925 926let asyKeyGenerator = cryptoFramework.createAsyKeyGenerator("ECC256"); 927let keyGenPromise = asyKeyGenerator.generateKeyPair(); 928keyGenPromise.then( keyPair => { 929 console.info("generateKeyPair success."); 930}).catch((error: BusinessError) => { 931 console.error("generateKeyPair error."); 932}); 933``` 934 935### convertKey 936 937convertKey(pubKey: DataBlob | null, priKey: DataBlob | null, callback: AsyncCallback\<KeyPair\>): void 938 939异步获取指定数据生成非对称密钥,通过注册回调函数获取结果。详情请看下方**密钥转换说明**。 940 941**系统能力:** SystemCapability.Security.CryptoFramework 942 943**参数:** 944 945| 参数名 | 类型 | 必填 | 说明 | 946| -------- | ----------- | ---- | ------------------------------ | 947| pubKey | [DataBlob](#datablob) \| null<sup>10+</sup> | 是 | 指定的公钥材料。如果公钥不需要转换,可直接传入null。API 10之前只支持DataBlob, API 10之后增加支持null。 | 948| priKey | [DataBlob](#datablob) \| null<sup>10+</sup> | 是 | 指定的私钥材料。如果私钥不需要转换,可直接传入null。API 10之前只支持DataBlob, API 10之后增加支持null。 | 949| callback | AsyncCallback\<[KeyPair](#keypair)> | 是 | 回调函数,用于获取非对称密钥。 | 950 951**错误码:** 952 953| 错误码ID | 错误信息 | 954| -------- | ---------------------- | 955| 401 | invalid parameters. | 956| 17620001 | memory error. | 957| 17630001 | crypto operation error. | 958 959**示例:** 960 961```ts 962import { BusinessError } from '@ohos.base'; 963 964let pubKeyArray = new Uint8Array([48, 89, 48, 19, 6, 7, 42, 134, 72, 206, 61, 2, 1, 6, 8, 42, 134, 72, 206, 61, 3, 1, 7, 3, 66, 0, 4, 83, 96, 142, 9, 86, 214, 126, 106, 247, 233, 92, 125, 4, 128, 138, 105, 246, 162, 215, 71, 81, 58, 202, 121, 26, 105, 211, 55, 130, 45, 236, 143, 55, 16, 248, 75, 167, 160, 167, 106, 2, 152, 243, 44, 68, 66, 0, 167, 99, 92, 235, 215, 159, 239, 28, 106, 124, 171, 34, 145, 124, 174, 57, 92]); 965let priKeyArray = new Uint8Array([48, 49, 2, 1, 1, 4, 32, 115, 56, 137, 35, 207, 0, 60, 191, 90, 61, 136, 105, 210, 16, 27, 4, 171, 57, 10, 61, 123, 40, 189, 28, 34, 207, 236, 22, 45, 223, 10, 189, 160, 10, 6, 8, 42, 134, 72, 206, 61, 3, 1, 7]); 966let pubKeyBlob: cryptoFramework.DataBlob = {data: pubKeyArray}; // Data of the public key. 967let priKeyBlob: cryptoFramework.DataBlob = {data: priKeyArray}; // Data of the private key. 968let asyKeyGenerator = cryptoFramework.createAsyKeyGenerator("ECC256"); 969asyKeyGenerator.convertKey(pubKeyBlob, priKeyBlob, (err, keyPair) => { 970 if (err) { 971 console.error("convertKey: error."); 972 return; 973 } 974 console.info("convertKey: success."); 975}) 976``` 977 978### convertKey 979 980convertKey(pubKey: DataBlob | null, priKey: DataBlob | null): Promise\<KeyPair> 981 982异步获取指定数据生成非对称密钥,通过Promise获取结果。详情请看下方**密钥转换说明**。 983 984**系统能力:** SystemCapability.Security.CryptoFramework 985 986**参数:** 987 988| 参数名 | 类型 | 必填 | 说明 | 989| ------ | -------- | ---- | ---------------- | 990| pubKey | [DataBlob](#datablob) \| null<sup>10+</sup> | 是 | 指定的公钥材料。如果公钥不需要转换,可直接传入null。API 10之前只支持DataBlob, API 10之后增加支持null。 | 991| priKey | [DataBlob](#datablob) \| null<sup>10+</sup> | 是 | 指定的私钥材料。如果私钥不需要转换,可直接传入null。API 10之前只支持DataBlob, API 10之后增加支持null。 | 992 993**返回值:** 994 995| 类型 | 说明 | 996| ----------------- | --------------------------------- | 997| Promise\<[KeyPair](#keypair)> | 使用Promise的方式获取非对称密钥。 | 998 999**错误码:** 1000 1001| 错误码ID | 错误信息 | 1002| -------- | ---------------------- | 1003| 401 | invalid parameters. | 1004| 17620001 | memory error. | 1005| 17630001 | crypto operation error. | 1006 1007**示例:** 1008 1009```ts 1010import { BusinessError } from '@ohos.base'; 1011 1012let pubKeyArray = new Uint8Array([48, 89, 48, 19, 6, 7, 42, 134, 72, 206, 61, 2, 1, 6, 8, 42, 134, 72, 206, 61, 3, 1, 7, 3, 66, 0, 4, 83, 96, 142, 9, 86, 214, 126, 106, 247, 233, 92, 125, 4, 128, 138, 105, 246, 162, 215, 71, 81, 58, 202, 121, 26, 105, 211, 55, 130, 45, 236, 143, 55, 16, 248, 75, 167, 160, 167, 106, 2, 152, 243, 44, 68, 66, 0, 167, 99, 92, 235, 215, 159, 239, 28, 106, 124, 171, 34, 145, 124, 174, 57, 92]); 1013let priKeyArray = new Uint8Array([48, 49, 2, 1, 1, 4, 32, 115, 56, 137, 35, 207, 0, 60, 191, 90, 61, 136, 105, 210, 16, 27, 4, 171, 57, 10, 61, 123, 40, 189, 28, 34, 207, 236, 22, 45, 223, 10, 189, 160, 10, 6, 8, 42, 134, 72, 206, 61, 3, 1, 7]); 1014let pubKeyBlob: cryptoFramework.DataBlob = {data: pubKeyArray}; // Data of the public key. 1015let priKeyBlob: cryptoFramework.DataBlob = {data: priKeyArray}; // Data of the private key. 1016let asyKeyGenerator = cryptoFramework.createAsyKeyGenerator("ECC256"); 1017let keyGenPromise = asyKeyGenerator.convertKey(pubKeyBlob, priKeyBlob); 1018keyGenPromise.then( keyPair => { 1019 console.info("convertKey success."); 1020}).catch((error: BusinessError) => { 1021 console.error("convertKey error."); 1022}); 1023``` 1024 1025**密钥转换说明** 1026 10271. 非对称密钥(RSA、ECC、DSA)的公钥和私钥调用getEncoded()方法后,分别返回X.509格式和PKCS#8格式的二进制数据,此数据可用于跨应用传输或持久化存储。 10282. 当调用convertKey方法将外来二进制数据转换为算法库非对称密钥对象时,公钥应满足ASN.1语法、X.509规范、DER编码格式,私钥应满足ASN.1语法、PKCS#8规范、DER编码格式。 10293. convertKey方法中,公钥和密钥二进制数据非必选项,可单独传入公钥或私钥的数据,生成对应只包含公钥或私钥的KeyPair对象。 1030 1031## cryptoFramework.createAsyKeyGeneratorBySpec<sup>10+</sup> 1032 1033createAsyKeyGeneratorBySpec(asyKeySpec: AsyKeySpec): AsyKeyGeneratorBySpec 1034 1035通过指定密钥参数,获取相应的非对称密钥生成器实例。 1036 1037支持的规格详见框架概述“[密钥生成规格](../../security/cryptoFramework-overview.md#密钥生成规格)”一节。 1038 1039**系统能力:** SystemCapability.Security.CryptoFramework 1040 1041**参数:** 1042 1043| 参数名 | 类型 | 必填 | 说明 | 1044| ------- | ------ | ---- | -------------------------------- | 1045| asyKeySpec | [AsyKeySpec](#asykeyspec10) | 是 | 密钥参数。非对称密钥生成器根据指定的这些参数生成公/私钥。 | 1046 1047**返回值:** 1048 1049| 类型 | 说明 | 1050| ----------------------------------------------- | -------------------------- | 1051| [AsyKeyGeneratorBySpec](#asykeygeneratorbyspec10) | 返回非对称密钥生成器实例。 | 1052 1053**错误码:** 1054 1055| 错误码ID | 错误信息 | 1056| -------- | ---------------------- | 1057| 401 | invalid parameters. | 1058| 801 | this operation is not supported. | 1059| 17620001 | memory error. | 1060 1061**示例:** 1062 1063```ts 1064// Set the common parameters contained in both the DSA1024 public and private keys. 1065function genDsa1024CommonSpecBigE() { 1066 let dsaCommonSpec: cryptoFramework.DSACommonParamsSpec = { 1067 algName : "DSA", 1068 specType : cryptoFramework.AsyKeySpecType.COMMON_PARAMS_SPEC, 1069 p : BigInt("0xed1501551b8ab3547f6355ffdc2913856ddeca198833dbd04f020e5f25e47c50e0b3894f7690a0d2ea5ed3a7be25c54292a698e1f086eb3a97deb4dbf04fcad2dafd94a9f35c3ae338ab35477e16981ded6a5b13d5ff20bf55f1b262303ad3a80af71aa6aa2354d20e9c82647664bdb6b333b7bea0a5f49d55ca40bc312a1729"), 1070 q : BigInt("0xd23304044019d5d382cfeabf351636c7ab219694ac845051f60b047b"), 1071 g : BigInt("0x2cc266d8bd33c3009bd67f285a257ba74f0c3a7e12b722864632a0ac3f2c17c91c2f3f67eb2d57071ef47aaa8f8e17a21ad2c1072ee1ce281362aad01dcbcd3876455cd17e1dd55d4ed36fa011db40f0bbb8cba01d066f392b5eaa9404bfcb775f2196a6bc20eeec3db32d54e94d87ecdb7a0310a5a017c5cdb8ac78597778bd"), 1072 } 1073 return dsaCommonSpec; 1074} 1075// Set full parameters contained in the DSA1024 public and private keys. 1076function genDsa1024KeyPairSpecBigE() { 1077 let dsaCommonSpec = genDsa1024CommonSpecBigE(); 1078 let dsaKeyPairSpec: cryptoFramework.DSAKeyPairSpec = { 1079 algName : "DSA", 1080 specType : cryptoFramework.AsyKeySpecType.KEY_PAIR_SPEC, 1081 params : dsaCommonSpec, 1082 sk : BigInt("0xa2dd2adb2d11392c2541930f61f1165c370aabd2d78d00342e0a2fd9"), 1083 pk : BigInt("0xae6b5d5042e758f3fc9a02d009d896df115811a75b5f7b382d8526270dbb3c029403fafb8573ba4ef0314ea86f09d01e82a14d1ebb67b0c331f41049bd6b1842658b0592e706a5e4d20c14b67977e17df7bdd464cce14b5f13bae6607760fcdf394e0b73ac70aaf141fa4dafd736bd0364b1d6e6c0d7683a5de6b9221e7f2d6b"), 1084 } 1085 return dsaKeyPairSpec; 1086} 1087 1088let asyKeyPairSpec = genDsa1024KeyPairSpecBigE(); // The JS input must be a positive number in big-endian format. 1089let asyKeyGeneratorBySpec = cryptoFramework.createAsyKeyGeneratorBySpec(asyKeyPairSpec); 1090``` 1091 1092## AsyKeyGeneratorBySpec<sup>10+</sup> 1093 1094非对称密钥生成器。在使用该类的方法前,需要先使用[createAsyKeyGeneratorBySpec()](#cryptoframeworkcreateasykeygeneratorbyspec10)方法构建一个AsyKeyGeneratorBySpec实例。 1095 1096### 属性 1097 1098**系统能力:** SystemCapability.Security.CryptoFramework 1099 1100| 名称 | 类型 | 可读 | 可写 | 说明 | 1101| ------- | ------ | ---- | ---- | -------------------------- | 1102| algName | string | 是 | 否 | 非对称密钥生成器的算法名。 | 1103 1104### generateKeyPair 1105 1106generateKeyPair(callback: AsyncCallback\<KeyPair>): void 1107 1108异步获取非对称密钥生成器生成的密钥,通过注册回调函数获取结果。 1109 1110当使用[COMMON_PARAMS_SPEC](#asykeyspectype10)类型的密钥参数来创建密钥生成器时,可以得到随机生成的密钥对;当使用[KEY_PAIR_SPEC](#asykeyspectype10)类型的密钥参数来创建密钥生成器时,可以得到各项数据与密钥参数一致的密钥对。 1111 1112**系统能力:** SystemCapability.Security.CryptoFramework 1113 1114**参数:** 1115 1116| 参数名 | 类型 | 必填 | 说明 | 1117| -------- | ----------------------- | ---- | ------------------------------ | 1118| callback | AsyncCallback\<[KeyPair](#keypair)> | 是 | 回调函数,用于获取非对称密钥。 | 1119 1120**错误码:** 1121 1122| 错误码ID | 错误信息 | 1123| -------- | ----------------------- | 1124| 401 | invalid parameters. | 1125| 17620001 | memory error. | 1126| 17630001 | crypto operation error. | 1127 1128**示例:** 1129 1130```ts 1131import { BusinessError } from '@ohos.base'; 1132 1133let asyKeyPairSpec: cryptoFramework.DSAKeyPairSpec; // dsa as example, asyKeyPairSpec specifies full parameters contained in the private and public keys. The generation process is omitted here. 1134let asyKeyGeneratorBySpec = cryptoFramework.createAsyKeyGeneratorBySpec(asyKeyPairSpec); 1135asyKeyGeneratorBySpec.generateKeyPair((err, keyPair) => { 1136 if (err) { 1137 console.error("generateKeyPair: error."); 1138 return; 1139 } 1140 console.info("generateKeyPair: success."); 1141}) 1142``` 1143 1144### generateKeyPair 1145 1146generateKeyPair(): Promise\<KeyPair> 1147 1148异步获取该非对称密钥生成器生成的密钥,通过Promise获取结果。 1149 1150当使用[COMMON_PARAMS_SPEC](#asykeyspectype10)类型的密钥参数来创建密钥生成器时,可以得到随机生成的密钥对;当使用[KEY_PAIR_SPEC](#asykeyspectype10)类型的密钥参数来创建密钥生成器时,可以得到各项数据与密钥参数一致的密钥对。 1151 1152**系统能力:** SystemCapability.Security.CryptoFramework 1153 1154**返回值:** 1155 1156| 类型 | 说明 | 1157| ----------------- | --------------------------------- | 1158| Promise\<[KeyPair](#keypair)> | 使用Promise的方式获取非对称密钥。 | 1159 1160**错误码:** 1161 1162| 错误码ID | 错误信息 | 1163| -------- | ---------------------- | 1164| 401 | invalid parameters. | 1165| 17620001 | memory error. | 1166| 17630001 | crypto operation error. | 1167 1168**示例:** 1169 1170```ts 1171import { BusinessError } from '@ohos.base'; 1172 1173let asyKeyPairSpec: cryptoFramework.DSAKeyPairSpec; // dsa as example, asyKeyPairSpec specifies full parameters contained in the private and public keys. The generation process is omitted here. 1174let asyKeyGeneratorBySpec = cryptoFramework.createAsyKeyGeneratorBySpec(asyKeyPairSpec); 1175let keyGenPromise = asyKeyGeneratorBySpec.generateKeyPair(); 1176keyGenPromise.then( keyPair => { 1177 console.info("generateKeyPair success."); 1178}).catch((error: BusinessError) => { 1179 console.error("generateKeyPair error."); 1180}); 1181``` 1182 1183### generatePriKey 1184 1185generatePriKey(callback: AsyncCallback\<PriKey>): void 1186 1187异步获取非对称密钥生成器生成的密钥,通过注册回调函数获取结果。 1188 1189当使用[PRIVATE_KEY_SPEC](#asykeyspectype10)类型的密钥参数来创建密钥生成器时,可以得到指定的私钥;当使用[KEY_PAIR_SPEC](#asykeyspectype10)类型的密钥参数来创建密钥生成器时,可以从生成的密钥对中获取指定的私钥。 1190 1191**系统能力:** SystemCapability.Security.CryptoFramework 1192 1193**参数:** 1194 1195| 参数名 | 类型 | 必填 | 说明 | 1196| -------- | ----------------------- | ---- | ------------------------------ | 1197| callback | AsyncCallback\<[PriKey](#prikey)> | 是 | 回调函数,用于获取非对称密钥。 | 1198 1199**错误码:** 1200 1201| 错误码ID | 错误信息 | 1202| -------- | ---------------------- | 1203| 401 | invalid parameters. | 1204| 17620001 | memory error. | 1205| 17630001 | crypto operation error. | 1206 1207**示例:** 1208 1209```ts 1210import { BusinessError } from '@ohos.base'; 1211 1212let asyKeyPairSpec: cryptoFramework.DSAKeyPairSpec; // dsa as example, asyKeyPairSpec specifies full parameters contained in the private and public keys. 1213let asyKeyGeneratorBySpec = cryptoFramework.createAsyKeyGeneratorBySpec(asyKeyPairSpec); 1214asyKeyGeneratorBySpec.generatePriKey((err, prikey) => { 1215 if (err) { 1216 console.error("generatePriKey: error."); 1217 return; 1218 } 1219 console.info("generatePriKey: success."); 1220}) 1221``` 1222 1223### generatePriKey 1224 1225generatePriKey(): Promise\<PriKey> 1226 1227异步获取该非对称密钥生成器生成的密钥,通过Promise获取结果。 1228 1229当使用[PRIVATE_KEY_SPEC](#asykeyspectype10)类型的密钥参数来创建密钥生成器时,可以得到指定的私钥;当使用[KEY_PAIR_SPEC](#asykeyspectype10)类型的密钥参数来创建密钥生成器时,可以从生成的密钥对中获取指定的私钥。 1230 1231**系统能力:** SystemCapability.Security.CryptoFramework 1232 1233**返回值:** 1234 1235| 类型 | 说明 | 1236| ----------------- | --------------------------------- | 1237| Promise\<[PriKey](#prikey)> | 使用Promise的方式获取非对称密钥。 | 1238 1239**错误码:** 1240 1241| 错误码ID | 错误信息 | 1242| -------- | ---------------------- | 1243| 401 | invalid parameters. | 1244| 17620001 | memory error. | 1245| 17630001 | crypto operation error. | 1246 1247**示例:** 1248 1249```ts 1250import { BusinessError } from '@ohos.base'; 1251 1252let asyKeyPairSpec: cryptoFramework.DSAKeyPairSpec; // dsa as example, asyKeyPairSpec specifies full parameters contained in the private and public keys. 1253let asyKeyGeneratorBySpec = cryptoFramework.createAsyKeyGeneratorBySpec(asyKeyPairSpec); 1254let keyGenPromise = asyKeyGeneratorBySpec.generatePriKey(); 1255keyGenPromise.then( priKey => { 1256 console.info("generatePriKey success."); 1257}).catch((error: BusinessError) => { 1258 console.error("generatePriKey error."); 1259}); 1260``` 1261 1262### generatePubKey 1263 1264generatePubKey(callback: AsyncCallback\<PubKey>): void 1265 1266异步获取非对称密钥生成器生成的密钥,通过注册回调函数获取结果。 1267 1268当使用[PUBLIC_KEY_SPEC](#asykeyspectype10)类型的密钥参数来创建密钥生成器时,可以得到指定的公钥;当使用[KEY_PAIR_SPEC](#asykeyspectype10)类型的密钥参数来创建密钥生成器时,可以从生成的密钥对中获取指定的公钥。 1269 1270**系统能力:** SystemCapability.Security.CryptoFramework 1271 1272**参数:** 1273 1274| 参数名 | 类型 | 必填 | 说明 | 1275| -------- | ----------------------- | ---- | ------------------------------ | 1276| callback | AsyncCallback\<[PubKey](#pubkey)> | 是 | 回调函数,用于获取非对称密钥。 | 1277 1278**错误码:** 1279 1280| 错误码ID | 错误信息 | 1281| -------- | ---------------------- | 1282| 401 | invalid parameters. | 1283| 17620001 | memory error. | 1284| 17630001 | crypto operation error. | 1285 1286**示例:** 1287 1288```ts 1289import { BusinessError } from '@ohos.base'; 1290 1291let asyKeyPairSpec: cryptoFramework.DSAKeyPairSpec; // dsa as example, asyKeyPairSpec specifies full parameters contained in the private and public keys. The generation process is omitted here. 1292let asyKeyGeneratorBySpec = cryptoFramework.createAsyKeyGeneratorBySpec(asyKeyPairSpec); 1293asyKeyGeneratorBySpec.generateKeyPair((err, pubKey) => { 1294 if (err) { 1295 console.error("generatePubKey: error."); 1296 return; 1297 } 1298 console.info("generatePubKey: success."); 1299}) 1300``` 1301 1302### generatePubKey 1303 1304generatePubKey(): Promise\<PubKey> 1305 1306异步获取该非对称密钥生成器生成的密钥,通过Promise获取结果。 1307 1308当使用[PUBLIC_KEY_SPEC](#asykeyspectype10)类型的密钥参数来创建密钥生成器时,可以得到指定的公钥;当使用[KEY_PAIR_SPEC](#asykeyspectype10)类型的密钥参数来创建密钥生成器时,可以从生成的密钥对中获取指定的公钥。 1309 1310**系统能力:** SystemCapability.Security.CryptoFramework 1311 1312**返回值:** 1313 1314| 类型 | 说明 | 1315| ----------------- | --------------------------------- | 1316| Promise\<[PubKey](#pubkey)> | 使用Promise的方式获取非对称密钥。 | 1317 1318**错误码:** 1319 1320| 错误码ID | 错误信息 | 1321| -------- | ---------------------- | 1322| 401 | invalid parameters. | 1323| 17620001 | memory error. | 1324| 17630001 | crypto operation error. | 1325 1326**示例:** 1327 1328```ts 1329import { BusinessError } from '@ohos.base'; 1330 1331let asyKeyPairSpec: cryptoFramework.DSAKeyPairSpec; // dsa as example, asyKeyPairSpec specifies full parameters contained in the private and public keys. The generation process is omitted here. 1332let asyKeyGeneratorBySpec = cryptoFramework.createAsyKeyGeneratorBySpec(asyKeyPairSpec); 1333let keyGenPromise = asyKeyGeneratorBySpec.generatePubKey(); 1334keyGenPromise.then( pubKey => { 1335 console.info("generatePubKey success."); 1336}).catch((error: BusinessError) => { 1337 console.error("generatePubKey error."); 1338}); 1339``` 1340 1341## cryptoFramework.createCipher 1342 1343createCipher(transformation: string): Cipher 1344 1345通过指定算法名称,获取相应的[Cipher](#cipher)实例。 1346 1347支持的规格详见框架概述“[加解密规格](../../security/cryptoFramework-overview.md#加解密规格)”一节。 1348 1349**系统能力:** SystemCapability.Security.CryptoFramework 1350 1351**参数:** 1352 1353| 参数名 | 类型 | 必填 | 说明 | 1354| -------------- | ------ | ---- | ------------------------------------------------------------ | 1355| transformation | string | 是 | 待生成Cipher的算法名称(含密钥长度)、加密模式以及填充方法的组合。<br/>具体取值详见框架概述“[加解密规格](../../security/cryptoFramework-overview.md#加解密规格)”一节中的“字符串参数”。 | 1356 1357> **说明:** 1358> 1359> 1. 目前对称加解密中,PKCS5和PKCS7的实现相同,其padding长度和分组长度保持一致(即PKCS5和PKCS7在3DES中均按照8字节填充,在AES中均按照16字节填充),另有NoPadding表示不填充。 1360> <br/>开发者需要自行了解密码学不同分组模式的差异,以便选择合适的参数规格。例如选择ECB和CBC模式时,建议启用填充,否则必须确保明文长度是分组大小的整数倍;选择其他模式时,可以不启用填充,此时密文长度和明文长度一致(即可能不是分组大小的整数倍)。 1361> 2. 使用RSA、SM2进行非对称加解密时,必须创建两个Cipher对象分别进行加密和解密操作,而不能对同一个Cipher对象进行加解密。对称加解密没有此要求(即只要算法规格一样,可以对同一个Cipher对象进行加解密操作)。 1362 1363**返回值:** 1364 1365| 类型 | 说明 | 1366| ----------------- | ------------------------ | 1367| [Cipher](#cipher) | 返回加解密生成器的对象。 | 1368 1369**错误码:** 1370 1371| 错误码ID | 错误信息 | 1372| -------- | ---------------------- | 1373| 401 | invalid parameters. | 1374| 801 | this operation is not supported. | 1375| 17620001 | memory error. | 1376 1377**示例:** 1378 1379```ts 1380import { BusinessError } from '@ohos.base'; 1381 1382let cipherAlgName = '3DES192|ECB|PKCS7'; 1383try { 1384 let cipher = cryptoFramework.createCipher(cipherAlgName); 1385 console.info(`cipher algName: ${cipher.algName}`); 1386} catch (error) { 1387 let e: BusinessError = error as BusinessError; 1388 console.error(`sync error, ${e.code}, ${e.message}`); 1389} 1390``` 1391 1392## Cipher 1393 1394提供加解密的算法操作功能,按序调用本类中的[init()](#init-1)、[update()](#update)、[doFinal()](#dofinal)方法,可以实现对称加密/对称解密/非对称加密/非对称解密。 1395 1396完整的加解密流程示例可参考开发指导中的“[使用加解密操作](../../security/cryptoFramework-guidelines.md#使用加解密操作)”一节。 1397 1398一次完整的加/解密流程在对称加密和非对称加密中略有不同: 1399 1400- 对称加解密:init为必选,update为可选(且允许多次update加/解密大数据),doFinal为必选;doFinal结束后可以重新init开始新一轮加/解密流程。 1401- RSA、SM2非对称加解密:init为必选,不支持update操作,doFinal为必选(允许连续多次doFinal加/解密大数据);RSA不支持重复init,切换加解密模式或填充方式时,需要重新创建Cipher对象。 1402 1403### 属性 1404 1405**系统能力:** SystemCapability.Security.CryptoFramework 1406 1407| 名称 | 类型 | 可读 | 可写 | 说明 | 1408| ------- | ------ | ---- | ---- | ---------------------------- | 1409| algName | string | 是 | 否 | 加解密生成器指定的算法名称。 | 1410 1411### init 1412 1413init(opMode: CryptoMode, key: Key, params: ParamsSpec | null, callback: AsyncCallback\<void>): void 1414 1415初始化加解密的[cipher](#cipher)对象,通过注册回调函数获取结果。 1416 1417必须在使用[createCipher](#cryptoframeworkcreatecipher)创建[Cipher](#cipher)实例后,才能使用本函数。 1418 1419**系统能力:** SystemCapability.Security.CryptoFramework 1420 1421**参数:** 1422 1423| 参数名 | 类型 | 必填 | 说明 | 1424| -------- | ------------------------- | ---- | ------------------------------------------------------------ | 1425| opMode | [CryptoMode](#cryptomode) | 是 | 加密或者解密模式。 | 1426| key | [Key](#key) | 是 | 指定加密或解密的密钥。 | 1427| params | [ParamsSpec](#paramsspec) \| null<sup>10+</sup> | 是 | 指定加密或解密的参数,对于ECB等没有参数的算法模式,可以传入null。API 10之前只支持ParamsSpec, API 10之后增加支持null。 | 1428| callback | AsyncCallback\<void> | 是 | 回调函数。当初始化成功,err为undefined,否则为错误对象。 | 1429 1430**错误码:** 1431 1432| 错误码ID | 错误信息 | 1433| -------- | --------------------------------------------------------- | 1434| 401 | invalid parameters. | 1435| 17620001 | memory error. | 1436| 17620002 | runtime error. | 1437| 17630001 | crypto operation error.| 1438 1439**示例:** 1440 1441```ts 1442import { BusinessError } from '@ohos.base'; 1443 1444let symKey: cryptoFramework.SymKey; // The process of generating the symmetric key is omitted here. 1445let cipher: cryptoFramework.Cipher; // The process of creating a Cipher instance is omitted here. 1446 1447cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, symKey, null, (err, ) => { 1448 if (err) { 1449 console.error(`Failed to init cipher, ${err.code}, ${err.message}`); 1450 } else { 1451 console.info(`Init cipher success`); 1452 // Perform subsequent operations such as update. 1453 } 1454}) 1455``` 1456 1457### init 1458 1459init(opMode: CryptoMode, key: Key, params: ParamsSpec | null): Promise\<void> 1460 1461初始化加解密的cipher对象,通过Promise获取结果。 1462 1463必须在使用[createCipher](#cryptoframeworkcreatecipher)创建[Cipher](#cipher)实例后,才能使用本函数。 1464 1465**系统能力:** SystemCapability.Security.CryptoFramework 1466 1467**参数:** 1468 1469| 参数名 | 类型 | 必填 | 说明 | 1470| ------ | ------------------------- | ---- | ------------------------------------------------------------ | 1471| opMode | [CryptoMode](#cryptomode) | 是 | 加密或者解密模式。 | 1472| key | [Key](#key) | 是 | 指定加密或解密的密钥。 | 1473| params | [ParamsSpec](#paramsspec) \| null<sup>10+</sup> | 是 | 指定加密或解密的参数,对于ECB等没有参数的算法模式,可以传入null。API 10之前只支持ParamsSpec, API 10之后增加支持null。 | 1474 1475**返回值:** 1476 1477| 类型 | 说明 | 1478| -------------- | -------------------------------------- | 1479| Promise\<void> | Promise对象。无返回结果的Promise对象。 | 1480 1481**错误码:** 1482 1483| 错误码ID | 错误信息 | 1484| -------- | ------------------------------------------------- | 1485| 401 | invalid parameters. | 1486| 17620001 | memory error. | 1487| 17620002 | runtime error. | 1488| 17630001 | crypto operation error.| 1489 1490**示例:** 1491 1492```ts 1493import { BusinessError } from '@ohos.base'; 1494 1495let symKey: cryptoFramework.SymKey; // The process of generating the symmetric key is omitted here. 1496let cipher: cryptoFramework.Cipher; // The process of creating a Cipher instance is omitted here. 1497cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, symKey, null) 1498 .then(() => { 1499 console.info(`Init cipher success`); 1500 // Perform subsequent operations such as update. 1501 }, (error: BusinessError) => { 1502 console.error(`Failed to init cipher, ${error.code}, ${error.message}`); 1503 }) 1504``` 1505 1506### update 1507 1508update(data: DataBlob, callback: AsyncCallback\<DataBlob>): void 1509 1510分段更新加密或者解密数据操作,通过注册回调函数获取加/解密数据。 1511 1512必须在对[Cipher](#cipher)实例使用[init()](init-1)初始化后,才能使用本函数。 1513 1514> **说明:** 1515> 1516> 1. 在进行对称加解密操作的时候,如果开发者对各个分组模式不够熟悉,建议对每次update和doFinal的结果都判断是否为null,并在结果不为null时取出其中的数据进行拼接,形成完整的密文/明文。这是因为选择的分组模式等各项规格都可能对update和doFinal结果产生影响。<br/>(例如对于ECB和CBC模式,不论update传入的数据是否为分组长度的整数倍,都会以分组作为基本单位进行加/解密,并输出本次update新产生的加/解密分组结果。<br/>可以理解为,update只要凑满一个新的分组就会有输出,如果没有凑满则此次update输出为null,把当前还没被加/解密的数据留着,等下一次update/doFinal传入数据的时候,拼接起来继续凑分组。<br/>最后doFinal的时候,会把剩下的还没加/解密的数据,根据[createCipher](#cryptoframeworkcreatecipher)时设置的padding模式进行填充,补齐到分组的整数倍长度,再输出剩余加解密结果。<br/>而对于可以将分组密码转化为流模式实现的模式,还可能出现密文长度和明文长度相同的情况等。) 1517> 2. 根据数据量,可以不调用update(即init完成后直接调用doFinal)或多次调用update。<br/> 1518> 算法库目前没有对update(单次或累计)的数据量设置大小限制,建议对于大数据量的对称加解密,采用多次update的方式传入数据。<br/> 1519> AES使用多次update操作的示例代码详见开发指导“[使用加解密操作](../../security/cryptoFramework-guidelines.md#使用加解密操作)”。 1520> 3. RSA、SM2非对称加解密不支持update操作。 1521 1522**系统能力:** SystemCapability.Security.CryptoFramework 1523 1524**参数:** 1525 1526| 参数名 | 类型 | 必填 | 说明 | 1527| -------- | ------------------------------------- | ---- | ------------------------------------------------------------ | 1528| data | [DataBlob](#datablob) | 是 | 加密或者解密的数据。data不能为null,也不允许传入{data: Uint8Array(空) }。 | 1529| callback | AsyncCallback\<[DataBlob](#datablob)> | 是 | 回调函数。当更新加/解密数据成功,err为undefined,data为此次更新的加/解密结果DataBlob;否则为错误对象。 | 1530 1531**错误码:** 1532 1533| 错误码ID | 错误信息 | 1534| -------- | ------------------------------------------- | 1535| 401 | invalid parameters. | 1536| 17620001 | memory error. | 1537| 17620002 | runtime error. | 1538| 17630001 | crypto operation error. | 1539 1540**示例:** 1541 1542```ts 1543import { BusinessError } from '@ohos.base'; 1544 1545function stringToUint8Array(str: string) { 1546 let arr = new Uint8Array(str.length); 1547 for (let i = 0, j = str.length; i < j; ++i) { 1548 arr[i] = str.charCodeAt(i); 1549 } 1550 return arr; 1551} 1552 1553let cipher: cryptoFramework.Cipher; // The process of creating a Cipher instance is omitted here. 1554// The init() process is omitted here. 1555let plainText: cryptoFramework.DataBlob = {data: stringToUint8Array('this is test!')}; 1556cipher.update(plainText, (err, output) => { // Example of the encryption process. 1557 if (err) { 1558 console.error(`Failed to update cipher`); 1559 } else { 1560 console.info(`Update cipher success`); 1561 if (output != null) { 1562 // Concatenate output.data to the ciphertext. 1563 } 1564 // Perform subsequent operations such as doFinal(). 1565 } 1566}) 1567``` 1568 1569### update 1570 1571update(data: DataBlob): Promise\<DataBlob> 1572 1573分段更新加密或者解密数据操作,通过Promise获取加/解密数据。 1574 1575必须在对[Cipher](#cipher)实例使用[init()](init-2)初始化后,才能使用本函数。 1576 1577> **说明:** 1578> 1579> 1. 在进行对称加解密操作的时候,如果开发者对各个分组模式不够熟悉,建议对每次update和doFinal的结果都判断是否为null,并在结果不为null时取出其中的数据进行拼接,形成完整的密文/明文。这是因为选择的分组模式等各项规格都可能对update和doFinal结果产生影响。 1580> <br/>(例如对于ECB和CBC模式,不论update传入的数据是否为分组长度的整数倍,都会以分组作为基本单位进行加/解密,并输出本次update新产生的加/解密分组结果。<br/>可以理解为,update只要凑满一个新的分组就会有输出,如果没有凑满则此次update输出为null,把当前还没被加/解密的数据留着,等下一次update/doFinal传入数据的时候,拼接起来继续凑分组。<br/>最后doFinal的时候,会把剩下的还没加/解密的数据,根据[createCipher](#cryptoframeworkcreatecipher)时设置的padding模式进行填充,补齐到分组的整数倍长度,再输出剩余加解密结果。<br/>而对于可以将分组密码转化为流模式实现的模式,还可能出现密文长度和明文长度相同的情况等。) 1581> 2. 根据数据量,可以不调用update(即init完成后直接调用doFinal)或多次调用update。<br/> 1582> 算法库目前没有对update(单次或累计)的数据量设置大小限制,建议对于大数据量的对称加解密,可以采用多次update的方式传入数据。<br/> 1583> AES使用多次update操作的示例代码详见开发指导“[使用加解密操作](../../security/cryptoFramework-guidelines.md#使用加解密操作)”。 1584> 3. RSA、SM2非对称加解密不支持update操作。 1585 1586**系统能力:** SystemCapability.Security.CryptoFramework 1587 1588**参数:** 1589 1590| 参数名 | 类型 | 必填 | 说明 | 1591| ---- | --------------------- | ---- | -------------------- | 1592| data | [DataBlob](#datablob) | 是 | 加密或者解密的数据。data不能为null,也不允许传入{data: Uint8Array(空) }。 | 1593 1594**返回值:** 1595 1596| 类型 | 说明 | 1597| ------------------------------- | ------------------------------------------------ | 1598| Promise\<[DataBlob](#datablob)> | Promise对象,返回此次更新的加/解密结果DataBlob。 | 1599 1600**错误码:** 1601 1602| 错误码ID | 错误信息 | 1603| -------- | -------------------------------------------- | 1604| 401 | invalid parameters. | 1605| 17620001 | memory error. | 1606| 17620002 | runtime error. | 1607| 17630001 | crypto operation error. | 1608 1609**示例:** 1610 1611```ts 1612import { BusinessError } from '@ohos.base'; 1613 1614function stringToUint8Array(str: string) { 1615 let arr = new Uint8Array(str.length); 1616 for (let i = 0, j = str.length; i < j; ++i) { 1617 arr[i] = str.charCodeAt(i); 1618 } 1619 return arr; 1620} 1621 1622let cipher: cryptoFramework.Cipher; // The process of creating a Cipher instance is omitted here. 1623// The init() process is omitted here. 1624let plainText: cryptoFramework.DataBlob = {data: stringToUint8Array('this is test!')}; 1625cipher.update(plainText) 1626 .then((output) => { 1627 console.info(`Update cipher success.`); 1628 if (output != null) { 1629 // Concatenate output.data to the ciphertext. 1630 } 1631 // Perform subsequent operations such as doFinal(). 1632 }, (error: BusinessError) => { 1633 console.info(`Update cipher failed.`); 1634 }) 1635``` 1636 1637### doFinal 1638 1639doFinal(data: DataBlob | null, callback: AsyncCallback\<DataBlob>): void 1640 1641(1)在对称加解密中,doFinal加/解密(分组模式产生的)剩余数据和本次传入的数据,最后结束加密或者解密数据操作,通过注册回调函数获取加密或者解密数据。<br/>如果数据量较小,可以在doFinal中一次性传入数据,而不使用update;如果在本次加解密流程中,已经使用[update](#update-4)传入过数据,可以在doFinal的data参数处传入null。<br/>根据对称加解密的模式不同,doFinal的输出有如下区别: 1642 1643- 对于GCM和CCM模式的对称加密:一次加密流程中,如果将每一次update和doFinal的结果拼接起来,会得到“密文+authTag”,即末尾的16字节(GCM模式)或12字节(CCM模式)是authTag,而其余部分均为密文。(也就是说,如果doFinal的data参数传入null,则doFinal的结果就是authTag)<br/>authTag需要填入解密时的[GcmParamsSpec](#gcmparamsspec)或[CcmParamsSpec](#ccmparamsspec);密文则作为解密时的入参data。 1644- 对于其他模式的对称加解密、GCM和CCM模式的对称解密:一次加/解密流程中,每一次update和doFinal的结果拼接起来,得到完整的明文/密文。 1645 1646(2)在RSA、SM2非对称加解密中,doFinal加/解密本次传入的数据,通过注册回调函数获取加密或者解密数据。如果数据量较大,可以多次调用doFinal,拼接结果得到完整的明文/密文。 1647 1648> **说明:** 1649> 1650> 1. 对称加解密中,调用doFinal标志着一次加解密流程已经完成,即[Cipher](#cipher)实例的状态被清除,因此当后续开启新一轮加解密流程时,需要重新调用init()并传入完整的参数列表进行初始化<br/>(比如即使是对同一个Cipher实例,采用同样的对称密钥,进行加密然后解密,则解密中调用init的时候仍需填写params参数,而不能直接省略为null)。 1651> 2. 如果遇到解密失败,需检查加解密数据和init时的参数是否匹配,包括GCM模式下加密得到的authTag是否填入解密时的GcmParamsSpec等。 1652> 3. doFinal的结果可能为null,因此使用.data字段访问doFinal结果的具体数据前,请记得先判断结果是否为null,避免产生异常。 1653> 4. RSA、SM2非对称加解密时多次doFinal操作的示例代码详见开发指导“[使用加解密操作](../../security/cryptoFramework-guidelines.md#使用加解密操作)”。 1654 1655**系统能力:** SystemCapability.Security.CryptoFramework 1656 1657**参数:** 1658 1659| 参数名 | 类型 | 必填 | 说明 | 1660| -------- | ------------------------------------- | ---- | ------------------------------------------------------------ | 1661| data | [DataBlob](#datablob) \| null<sup>10+</sup> | 是 | 加密或者解密的数据。在对称加解密中允许为null,但不允许传入{data: Uint8Array(空) }。API 10之前只支持DataBlob, API 10之后增加支持null。 | 1662| callback | AsyncCallback\<[DataBlob](#datablob)> | 是 | 回调函数。当最终加/解密数据成功,err为undefined,data为剩余数据的加/解密结果DataBlob;否则为错误对象。 | 1663 1664**错误码:** 1665 1666| 错误码ID | 错误信息 | 1667| -------- | ----------------------- | 1668| 401 | invalid parameters. | 1669| 17620001 | memory error. | 1670| 17620002 | runtime error. | 1671| 17630001 | crypto operation error. | 1672 1673**示例:** 1674 1675```ts 1676import { BusinessError } from '@ohos.base'; 1677 1678let cipher: cryptoFramework.Cipher; // The process of creating a Cipher instance is omitted here. 1679let data: cryptoFramework.DataBlob; // The process of preparing the data to encrypt or decrypt is omitted here. 1680// The init() and update() processes are omitted here. 1681cipher.doFinal(data, (err, output) => { 1682 if (err) { 1683 console.error(`Failed to finalize cipher, ${err.code}, ${err.message}`); 1684 } else { 1685 console.info(`Finalize cipher success`); 1686 if (output != null) { 1687 // Concatenate output.data to obtain the complete plaintext/ciphertext (and authTag). 1688 } 1689 } 1690}) 1691``` 1692 1693### doFinal 1694 1695doFinal(data: DataBlob | null): Promise\<DataBlob> 1696 1697(1)在对称加解密中,doFinal加/解密(分组模式产生的)剩余数据和本次传入的数据,最后结束加密或者解密数据操作,通过Promise获取加密或者解密数据。<br/>如果数据量较小,可以在doFinal中一次性传入数据,而不使用update;如果在本次加解密流程中,已经使用update传入过数据,可以在doFinal的data参数处传入null。<br/>根据对称加解密的模式不同,doFinal的输出有如下区别: 1698 1699- 对于GCM和CCM模式的对称加密:一次加密流程中,如果将每一次update和doFinal的结果拼接起来,会得到“密文+authTag”,即末尾的16字节(GCM模式)或12字节(CCM模式)是authTag,而其余部分均为密文。(也就是说,如果doFinal的data参数传入null,则doFinal的结果就是authTag)<br/>authTag需要填入解密时的[GcmParamsSpec](#gcmparamsspec)或[CcmParamsSpec](#ccmparamsspec);密文则作为解密时的入参data。 1700- 对于其他模式的对称加解密、GCM和CCM模式的对称解密:一次加/解密流程中,每一次update和doFinal的结果拼接起来,得到完整的明文/密文。 1701 1702(2)在RSA、SM2非对称加解密中,doFinal加/解密本次传入的数据,通过Promise获取加密或者解密数据。如果数据量较大,可以多次调用doFinal,拼接结果得到完整的明文/密文。 1703 1704> **说明:** 1705> 1706> 1. 对称加解密中,调用doFinal标志着一次加解密流程已经完成,即[Cipher](#cipher)实例的状态被清除,因此当后续开启新一轮加解密流程时,需要重新调用init()并传入完整的参数列表进行初始化<br/>(比如即使是对同一个Cipher实例,采用同样的对称密钥,进行加密然后解密,则解密中调用init的时候仍需填写params参数,而不能直接省略为null)。 1707> 2. 如果遇到解密失败,需检查加解密数据和init时的参数是否匹配,包括GCM模式下加密得到的authTag是否填入解密时的GcmParamsSpec等。 1708> 3. doFinal的结果可能为null,因此使用.data字段访问doFinal结果的具体数据前,请记得先判断结果是否为null,避免产生异常。 1709> 4. RSA、SM2非对称加解密时多次doFinal操作的示例代码详见开发指导“[使用加解密操作](../../security/cryptoFramework-guidelines.md#使用加解密操作)”。 1710 1711**系统能力:** SystemCapability.Security.CryptoFramework 1712 1713**参数:** 1714 1715| 参数名 | 类型 | 必填 | 说明 | 1716| ---- | --------------------- | ---- | -------------------- | 1717| data | [DataBlob](#datablob) \| null<sup>10+</sup> | 是 | 加密或者解密的数据。data参数允许为null,但不允许传入{data: Uint8Array(空) }。API 10之前只支持DataBlob, API 10之后增加支持null。 | 1718 1719**返回值:** 1720 1721| 类型 | 说明 | 1722| ------------------------------- | ------------------------------------------------ | 1723| Promise\<[DataBlob](#datablob)> | Promise对象,返回剩余数据的加/解密结果DataBlob。 | 1724 1725**错误码:** 1726 1727| 错误码ID | 错误信息 | 1728| -------- | -------------------------------------------- | 1729| 401 | invalid parameters. | 1730| 17620001 | memory error. | 1731| 17620002 | runtime error. | 1732| 17630001 | crypto operation error. | 1733 1734**示例:** 1735 1736```ts 1737import { BusinessError } from '@ohos.base'; 1738 1739let cipher: cryptoFramework.Cipher; // The process of creating a Cipher instance is omitted here. 1740let data: cryptoFramework.DataBlob; // The process of preparing the data to encrypt or decrypt is omitted here. 1741// The init() and update() processes are omitted here. 1742cipher.doFinal(data) 1743 .then(output => { 1744 console.info(`Finalize cipher success`); 1745 if (output != null) { 1746 // Concatenate output.data to obtain the complete plaintext/ciphertext (and authTag). 1747 } 1748 }, (error: BusinessError) => { 1749 console.error(`Failed to finalize cipher, ${error.code}, ${error.message}`); 1750 }) 1751``` 1752 1753**使用RSA加密的callback完整示例:** 1754 1755```ts 1756function stringToUint8Array(str: string) { 1757 let arr = new Uint8Array(str.length); 1758 for (let i = 0, j = str.length; i < j; ++i) { 1759 arr[i] = str.charCodeAt(i); 1760 } 1761 return arr; 1762} 1763 1764let rsaGenerator = cryptoFramework.createAsyKeyGenerator("RSA1024|PRIMES_2"); 1765let cipher = cryptoFramework.createCipher("RSA1024|PKCS1"); 1766rsaGenerator.generateKeyPair((err, keyPair) => { 1767 let pubKey = keyPair.pubKey; 1768 cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, pubKey, null, (err, data) => { 1769 let plainText = "this is cipher text"; 1770 let input: cryptoFramework.DataBlob = {data: stringToUint8Array(plainText) }; 1771 cipher.doFinal(input, (err, data) => { 1772 AlertDialog.show({ message: "EncryptOutPut is " + data.data} ); 1773 }); 1774 }); 1775}); 1776``` 1777 1778**使用RSA加密的Promise完整示例:** 1779 1780```ts 1781function stringToUint8Array(str: string) { 1782 let arr = new Uint8Array(str.length); 1783 for (let i = 0, j = str.length; i < j; ++i) { 1784 arr[i] = str.charCodeAt(i); 1785 } 1786 return arr; 1787} 1788 1789let rsaGenerator = cryptoFramework.createAsyKeyGenerator("RSA1024|PRIMES_2"); 1790let cipher = cryptoFramework.createCipher("RSA1024|PKCS1"); 1791let keyGenPromise = rsaGenerator.generateKeyPair(); 1792keyGenPromise.then((rsaKeyPair: cryptoFramework.KeyPair): Promise<void> => { 1793 let pubKey = rsaKeyPair.pubKey; 1794 return cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, pubKey, null); // Pass in the private key and DECRYPT_MODE to initialize the decryption mode. 1795}).then(() => { 1796 let plainText = "this is cipher text"; 1797 let input: cryptoFramework.DataBlob = { data: stringToUint8Array(plainText) }; 1798 return cipher.doFinal(input); 1799}).then(dataBlob => { 1800 console.info("EncryptOutPut is " + dataBlob.data); 1801}); 1802``` 1803 1804> **说明:** 1805> 1806> 更多加解密流程的完整示例可参考开发指导中的“[使用加解密操作](../../security/cryptoFramework-guidelines.md#使用加解密操作)”一节。 1807 1808### setCipherSpec<sup>10+</sup> 1809 1810setCipherSpec(itemType: CipherSpecItem, itemValue: Uint8Array): void 1811 1812设置加解密参数。常用的加解密参数可以直接通过[createCipher](#cryptoframeworkcreatecipher) 来指定,剩余参数可以通过本接口指定。当前只支持RSA算法。 1813 1814**系统能力:** SystemCapability.Security.CryptoFramework 1815 1816**参数:** 1817 1818| 参数名 | 类型 | 必填 | 说明 | 1819| -------- | -------------------- | ---- | ---------- | 1820| itemType | [CipherSpecItem](#cipherspecitem10) | 是 | 用于指定需要设置的加解密参数。 | 1821| itemValue | Uint8Array | 是 | 用于指定加解密参数的具体值。 | 1822 1823**错误码:** 1824 1825| 错误码ID | 错误信息 | 1826| -------- | ---------------------- | 1827| 401 | invalid parameters. | 1828| 801 | this operation is not supported. | 1829| 17620001 | memory error. | 1830| 17630001 | crypto operation error. | 1831 1832**示例:** 1833 1834```ts 1835let cipher: cryptoFramework.Cipher; // The process of generating the Cipher instance is omitted here. 1836let pSource = new Uint8Array([1,2,3,4]); 1837cipher.setCipherSpec(cryptoFramework.CipherSpecItem.OAEP_MGF1_PSRC_UINT8ARR, pSource); 1838``` 1839 1840### getCipherSpec<sup>10+</sup> 1841 1842getCipherSpec(itemType: CipherSpecItem): string | Uint8Array 1843 1844获取加解密参数。当前只支持RSA算法。 1845 1846**系统能力:** SystemCapability.Security.CryptoFramework 1847 1848**参数:** 1849 1850| 参数名 | 类型 | 必填 | 说明 | 1851| ------ | -------- | ---- | ---------- | 1852| itemType | [CipherSpecItem](#cipherspecitem10) | 是 | 用于指定需要获取的加解密参数。 | 1853 1854**返回值:** 1855 1856| 类型 | 说明 | 1857| -------------- | ----------- | 1858| string\|Uint8Array | 获取的加解密参数的具体值。 | 1859 1860**错误码:** 1861 1862| 错误码ID | 错误信息 | 1863| -------- | ---------------------- | 1864| 401 | invalid parameters. | 1865| 801 | this operation is not supported. | 1866| 17620001 | memory error. | 1867| 17630001 | crypto operation error. | 1868 1869**示例:** 1870 1871```ts 1872let cipher: cryptoFramework.Cipher; // The process of generating the Cipher instance is omitted here. 1873let mdName = cipher.getCipherSpec(cryptoFramework.CipherSpecItem.OAEP_MD_NAME_STR); 1874``` 1875 1876## cryptoFramework.createSign 1877 1878createSign(algName: string): Sign 1879 1880Sign实例生成。 1881 1882支持的规格详见框架概述“[签名验签规格](../../security/cryptoFramework-overview.md#签名验签规格)”一节。 1883 1884**系统能力:** SystemCapability.Security.CryptoFramework 1885 1886**参数:** 1887 1888| 参数名 | 类型 | 必填 | 说明 | 1889| ------- | ------ | ---- | ------------------------------------------------------------ | 1890| algName | string | 是 | 指定签名算法:RSA,ECC,DSA或SM2<sup>10+</sup>。使用RSA PKCS1模式时需要设置摘要,使用RSA PSS模式时需要设置摘要和掩码摘要。 | 1891 1892**返回值**: 1893 1894| 类型 | 说明 | 1895| ---- | ---------------------------------- | 1896| Sign | 返回由输入算法指定生成的Sign对象。 | 1897 1898**错误码:** 1899 1900| 错误码ID | 错误信息 | 1901| -------- | ---------------------- | 1902| 401 | invalid parameters. | 1903| 801 | this operation is not supported. | 1904| 17620001 | memory error. | 1905 1906**示例:** 1907 1908```ts 1909let signer1 = cryptoFramework.createSign("RSA1024|PKCS1|SHA256"); 1910 1911let signer2 = cryptoFramework.createSign("RSA1024|PSS|SHA256|MGF1_SHA256"); 1912 1913let signer3 = cryptoFramework.createSign("ECC224|SHA256"); 1914 1915let signer4 = cryptoFramework.createSign("DSA2048|SHA256"); 1916``` 1917 1918## Sign 1919 1920Sign类,使用Sign方法之前需要创建该类的实例进行操作,通过[createSign(algName: string): Sign](#cryptoframeworkcreatesign)方法构造此实例。按序调用本类中的init、update、sign方法完成签名操作。签名操作的示例代码详见开发指导“[使用签名验签操作](../../security/cryptoFramework-guidelines.md#使用签名验签操作)”。 1921 1922Sign类不支持重复初始化,当业务方需要使用新密钥签名时,需要重新创建新Sign对象并调用init初始化。 1923 1924业务方使用时,在createSign时确定签名的模式,调用init接口设置密钥。 1925 1926当待签名数据较短时,可在init初始化后,(无需update)直接调用sign接口传入原文数据进行签名。 1927 1928当待签名数据较长时,可通过update接口分段传入切分后的原文数据,最后调用sign接口对整体原文数据进行签名。 1929 1930当使用update分段传入原文时,sign接口API 10之前只支持传入DataBlob, API 10之后增加支持null。业务方可在循环中调用update接口,循环结束后调用sign进行签名。 1931 1932### 属性 1933 1934**系统能力:** SystemCapability.Security.CryptoFramework 1935 1936| 名称 | 类型 | 可读 | 可写 | 说明 | 1937| ------- | ------ | ---- | ---- | ---------------------------- | 1938| algName | string | 是 | 否 | 签名指定的算法名称。 | 1939 1940### init 1941 1942init(priKey: PriKey, callback: AsyncCallback\<void>): void 1943 1944使用私钥初始化Sign对象,通过注册回调函数获取结果。 1945 1946Sign类暂不支持重复init。 1947 1948**系统能力:** SystemCapability.Security.CryptoFramework 1949 1950**参数:** 1951 1952| 参数名 | 类型 | 必填 | 说明 | 1953| -------- | -------------------- | ---- | ---------------- | 1954| priKey | [PriKey](#prikey) | 是 | 用于Sign的初始化。 | 1955| callback | AsyncCallback\<void> | 是 | 回调函数。 | 1956 1957**错误码:** 1958 1959| 错误码ID | 错误信息 | 1960| -------- | ---------------------- | 1961| 401 | invalid parameters. | 1962| 17620001 | memory error. | 1963| 17620002 | runtime error. | 1964| 17630001 | crypto operation error. | 1965 1966### init 1967 1968init(priKey: PriKey): Promise\<void> 1969 1970使用私钥初始化Sign对象,通过Promise获取结果。 1971 1972Sign类暂不支持重复init。 1973 1974**系统能力:** SystemCapability.Security.CryptoFramework 1975 1976**参数:** 1977 1978| 参数名 | 类型 | 必填 | 说明 | 1979| ------ | ---- | ---- | ---------------- | 1980| priKey | [PriKey](#prikey) | 是 | 用于Sign的初始化。 | 1981 1982**返回值:** 1983 1984| 类型 | 说明 | 1985| -------------- | ------------- | 1986| Promise\<void> | Promise对象。 | 1987 1988**错误码:** 1989 1990| 错误码ID | 错误信息 | 1991| -------- | ---------------------- | 1992| 401 | invalid parameters. | 1993| 17620001 | memory error. | 1994| 17620002 | runtime error. | 1995| 17630001 | crypto operation error. | 1996 1997### update 1998 1999update(data: DataBlob, callback: AsyncCallback\<void>): void 2000 2001追加待签名数据,通过注册回调函数完成更新。 2002 2003必须在对[Sign](#sign)实例使用[init()](#init-2)初始化后,才能使用本函数。 2004 2005> **说明:** 2006> 2007> 根据数据量,可以不调用update(即[init](#init-2)完成后直接调用[sign](#sign-1))或多次调用update。<br/> 2008> 算法库目前没有对update(单次或累计)的数据量设置大小限制,建议对于大数据量的签名操作,采用多次update的方式传入数据,避免一次性申请过大内存。<br/> 2009> 签名使用多次update操作的示例代码详见开发指导“[使用签名验签操作](../../security/cryptoFramework-guidelines.md#使用签名验签操作)”。 2010 2011**系统能力:** SystemCapability.Security.CryptoFramework 2012 2013**参数:** 2014 2015| 参数名 | 类型 | 必填 | 说明 | 2016| -------- | --------------------- | ---- | ------------ | 2017| data | [DataBlob](#datablob) | 是 | 传入的消息。 | 2018| callback | AsyncCallback\<void> | 是 | 回调函数。 | 2019 2020**错误码:** 2021 2022| 错误码ID | 错误信息 | 2023| -------- | ---------------------- | 2024| 401 | invalid parameters. | 2025| 17620001 | memory error. | 2026| 17620002 | runtime error. | 2027| 17630001 | crypto operation error. | 2028 2029### update 2030 2031update(data: DataBlob): Promise\<void> 2032 2033追加待签名数据,通过Promise方式完成更新。 2034 2035必须在对[Sign](#sign)实例使用[init()](#init-3)初始化后,才能使用本函数。 2036 2037> **说明:** 2038> 2039> 根据数据量,可以不调用update(即[init](#init-3)完成后直接调用[sign](#sign-2))或多次调用update。<br/> 2040> 算法库目前没有对update(单次或累计)的数据量设置大小限制,建议对于大数据量的签名操作,采用多次update的方式传入数据,避免一次性申请过大内存。<br/> 2041> 签名使用多次update操作的示例代码详见开发指导“[使用签名验签操作](../../security/cryptoFramework-guidelines.md#使用签名验签操作)”。 2042 2043**系统能力:** SystemCapability.Security.CryptoFramework 2044 2045**参数:** 2046 2047| 参数名 | 类型 | 必填 | 说明 | 2048| ------ | -------- | ---- | ---------- | 2049| data | [DataBlob](#datablob) | 是 | 传入的消息。 | 2050 2051**返回值:** 2052 2053| 类型 | 说明 | 2054| -------------- | ------------- | 2055| Promise\<void> | Promise对象。 | 2056 2057**错误码:** 2058 2059| 错误码ID | 错误信息 | 2060| -------- | ---------------------- | 2061| 401 | invalid parameters. | 2062| 17620001 | memory error. | 2063| 17620002 | runtime error. | 2064| 17630001 | crypto operation error. | 2065 2066### sign 2067 2068sign(data: DataBlob | null, callback: AsyncCallback\<DataBlob>): void 2069 2070对数据进行签名,通过注册回调函数获取签名结果。 2071 2072**系统能力:** SystemCapability.Security.CryptoFramework 2073 2074**参数:** 2075 2076| 参数名 | 类型 | 必填 | 说明 | 2077| -------- | -------------------- | ---- | ---------- | 2078| data | [DataBlob](#datablob) \| null<sup>10+</sup> | 是 | 传入的消息。API 10之前只支持DataBlob, API 10之后增加支持null。 | 2079| callback | AsyncCallback\<[DataBlob](#datablob) > | 是 | 回调函数。 | 2080 2081**错误码:** 2082 2083| 错误码ID | 错误信息 | 2084| -------- | ---------------------- | 2085| 401 | invalid parameters. | 2086| 17620001 | memory error. | 2087| 17620002 | runtime error. | 2088| 17630001 | crypto operation error. | 2089 2090### sign 2091 2092sign(data: DataBlob | null): Promise\<DataBlob> 2093 2094对数据进行签名,通过Promise方式返回签名结果。 2095 2096**系统能力:** SystemCapability.Security.CryptoFramework 2097 2098**参数:** 2099 2100| 参数名 | 类型 | 必填 | 说明 | 2101| ------ | -------- | ---- | ---------- | 2102| data | [DataBlob](#datablob) \| null<sup>10+</sup> | 是 | 传入的消息。 | 2103 2104**返回值:** 2105 2106| 类型 | 说明 | 2107| -------------- | ------------- | 2108| Promise\<void> | Promise对象。 | 2109 2110**错误码:** 2111 2112| 错误码ID | 错误信息 | 2113| -------- | ---------------------- | 2114| 401 | invalid parameters. | 2115| 17620001 | memory error. | 2116| 17620002 | runtime error. | 2117| 17630001 | crypto operation error. | 2118 2119**callback示例:** 2120 2121```ts 2122function stringToUint8Array(str: string) { 2123 let arr = new Uint8Array(str.length); 2124 for (let i = 0, j = str.length; i < j; ++i) { 2125 arr[i] = str.charCodeAt(i); 2126 } 2127 return arr; 2128} 2129 2130let globalKeyPair: cryptoFramework.KeyPair; 2131let signMessageBlob: cryptoFramework.DataBlob; 2132let plan1 = "This is Sign test plan1"; // The first segment of the data. 2133let plan2 = "This is Sign test plan2"; // The second segment of the data. 2134let input1: cryptoFramework.DataBlob = { data: stringToUint8Array(plan1) }; 2135let input2: cryptoFramework.DataBlob = { data: stringToUint8Array(plan2) }; 2136 2137function signMessageCallback() { 2138 let rsaGenerator = cryptoFramework.createAsyKeyGenerator("RSA1024|PRIMES_2"); 2139 let signer = cryptoFramework.createSign("RSA1024|PKCS1|SHA256"); 2140 rsaGenerator.generateKeyPair((err, keyPair) => { 2141 globalKeyPair = keyPair; 2142 let priKey = globalKeyPair.priKey; 2143 signer.init(priKey, err => { 2144 signer.update(input1, err => { // add first segment of data 2145 signer.sign(input2, (err, data) => { // add second segment of data, sign input1 and input2 2146 signMessageBlob = data; 2147 AlertDialog.show({message: "res" + signMessageBlob.data}); 2148 }); 2149 }); 2150 }); 2151 }); 2152} 2153``` 2154 2155**Promise示例:** 2156 2157```ts 2158function stringToUint8Array(str: string) { 2159 let arr = new Uint8Array(str.length); 2160 for (let i = 0, j = str.length; i < j; ++i) { 2161 arr[i] = str.charCodeAt(i); 2162 } 2163 return arr; 2164} 2165 2166let globalKeyPair: cryptoFramework.KeyPair; 2167let signMessageBlob: cryptoFramework.DataBlob; 2168let plan1 = "This is Sign test plan1"; // The first segment of the data. 2169let plan2 = "This is Sign test plan2"; // The second segment of the data. 2170let input1: cryptoFramework.DataBlob = { data: stringToUint8Array(plan1) }; 2171let input2: cryptoFramework.DataBlob = { data: stringToUint8Array(plan2) }; 2172 2173function signMessagePromise() { 2174 let rsaGenerator = cryptoFramework.createAsyKeyGenerator("RSA1024|PRIMES_2"); 2175 let signer = cryptoFramework.createSign("RSA1024|PKCS1|SHA256"); // From API version 10, a Sign instance can be created by specifying a string parameter defining the key specifications. 2176 let keyGenPromise = rsaGenerator.generateKeyPair(); 2177 keyGenPromise.then(keyPair => { 2178 globalKeyPair = keyPair; 2179 let priKey = globalKeyPair.priKey; 2180 return signer.init(priKey); 2181 }).then(() => { 2182 return signer.update(input1); 2183 }).then(() => { 2184 return signer.sign(input2); 2185 }).then(dataBlob => { 2186 signMessageBlob = dataBlob; 2187 console.info("sign output is " + signMessageBlob.data); 2188 }); 2189} 2190``` 2191 2192### setSignSpec<sup>10+</sup> 2193 2194setSignSpec(itemType: SignSpecItem, itemValue: number): void 2195 2196设置签名参数。常用的签名参数可以直接通过[createSign](#cryptoframeworkcreatesign) 来指定,剩余参数可以通过本接口指定。 2197 2198当前只支持RSA算法。 2199 2200**系统能力:** SystemCapability.Security.CryptoFramework 2201 2202**参数:** 2203 2204| 参数名 | 类型 | 必填 | 说明 | 2205| -------- | -------------------- | ---- | ---------- | 2206| itemType | [SignSpecItem](#signspecitem10) | 是 | 用于指定需要设置的签名参数。 | 2207| itemValue | number | 是 | 用于指定签名参数的具体值。 | 2208 2209**错误码:** 2210 2211| 错误码ID | 错误信息 | 2212| -------- | ---------------------- | 2213| 401 | invalid parameters. | 2214| 801 | this operation is not supported. | 2215| 17620001 | memory error. | 2216| 17630001 | crypto operation error. | 2217 2218**示例:** 2219 2220```ts 2221let signer: cryptoFramework.Sign; // The process of generating the Sign instance is omitted here. 2222let setN = 20; 2223signer.setSignSpec(cryptoFramework.SignSpecItem.PSS_SALT_LEN_NUM, setN); 2224``` 2225 2226### getSignSpec<sup>10+</sup> 2227 2228getSignSpec(itemType: SignSpecItem): string | number 2229 2230获取签名参数。当前只支持RSA算法。 2231 2232**系统能力:** SystemCapability.Security.CryptoFramework 2233 2234**参数:** 2235 2236| 参数名 | 类型 | 必填 | 说明 | 2237| ------ | -------- | ---- | ---------- | 2238| itemType | [SignSpecItem](#signspecitem10) | 是 | 用于指定需要获取的签名参数。 | 2239 2240**返回值:** 2241 2242| 类型 | 说明 | 2243| -------------- | ----------- | 2244| string\|number | 获取的签名参数的具体值。 | 2245 2246**错误码:** 2247 2248| 错误码ID | 错误信息 | 2249| -------- | ---------------------- | 2250| 401 | invalid parameters. | 2251| 801 | this operation is not supported. | 2252| 17620001 | memory error. | 2253| 17630001 | crypto operation error. | 2254 2255**示例:** 2256 2257```ts 2258let signer: cryptoFramework.Sign; // The process of generating the Sign instance is omitted here. 2259let saltLen = signer.getSignSpec(cryptoFramework.SignSpecItem.PSS_SALT_LEN_NUM); 2260``` 2261 2262## cryptoFramework.createVerify 2263 2264createVerify(algName: string): Verify 2265 2266Verify实例生成。 2267 2268支持的规格详见框架概述“[签名验签规格](../../security/cryptoFramework-overview.md#签名验签规格)”一节。 2269 2270**系统能力:** SystemCapability.Security.CryptoFramework 2271 2272**参数:** 2273 2274| 参数名 | 类型 | 必填 | 说明 | 2275| ------- | ------ | ---- | ------------------------------------------------------------ | 2276| algName | string | 是 | 指定签名算法:RSA,ECC,DSA或SM2<sup>10+</sup>,。使用RSA PKCS1模式时需要设置摘要,使用RSA PSS模式时需要设置摘要和掩码摘要。 | 2277 2278**返回值**: 2279 2280| 类型 | 说明 | 2281| ------ | ------------------------------------ | 2282| Verify | 返回由输入算法指定生成的Verify对象。 | 2283 2284**错误码:** 2285 2286| 错误码ID | 错误信息 | 2287| -------- | ---------------------- | 2288| 401 | invalid parameters. | 2289| 801 | this operation is not supported. | 2290| 17620001 | memory error. | 2291 2292**示例:** 2293 2294```ts 2295let verifyer1 = cryptoFramework.createVerify("RSA1024|PKCS1|SHA256"); 2296 2297let verifyer2 = cryptoFramework.createVerify("RSA1024|PSS|SHA256|MGF1_SHA256") 2298``` 2299 2300## Verify 2301 2302Verify类,使用Verify方法之前需要创建该类的实例进行操作,通过[createVerify(algName: string): Verify](#cryptoframeworkcreateverify)方法构造此实例。按序调用本类中的init、update、verify方法完成签名操作。验签操作的示例代码详见开发指导“[使用签名验签操作](../../security/cryptoFramework-guidelines.md#使用签名验签操作)”。 2303 2304Verify类不支持重复初始化,当业务方需要使用新密钥验签时,需要重新创建新Verify对象并调用init初始化。 2305 2306业务方使用时,在createVerify时确定验签的模式,调用init接口设置密钥。 2307 2308当被签名的消息较短时,可在init初始化后,(无需update)直接调用verify接口传入被签名的消息和签名(signatureData)进行验签。 2309 2310当被签名的消息较长时,可通过update接口分段传入被签名的消息,最后调用verify接口对消息全文进行验签。verify接口的data入参在API 10之前只支持DataBlob, API 10之后增加支持null。业务方可在循环中调用update接口,循环结束后调用verify传入签名(signatureData)进行验签。 2311 2312### 属性 2313 2314**系统能力:** SystemCapability.Security.CryptoFramework 2315 2316| 名称 | 类型 | 可读 | 可写 | 说明 | 2317| ------- | ------ | ---- | ---- | ---------------------------- | 2318| algName | string | 是 | 否 | 验签指定的算法名称。 | 2319 2320### init 2321 2322init(pubKey: PubKey, callback: AsyncCallback\<void>): void 2323 2324传入公钥初始化Verify对象,通过注册回调函数获取结果。 2325 2326**系统能力:** SystemCapability.Security.CryptoFramework 2327 2328**参数:** 2329 2330| 参数名 | 类型 | 必填 | 说明 | 2331| -------- | -------------------- | ---- | ------------------------------ | 2332| pubKey | [PubKey](#pubkey) | 是 | 公钥对象,用于Verify的初始化。 | 2333| callback | AsyncCallback\<void> | 是 | 回调函数。 | 2334 2335**错误码:** 2336 2337| 错误码ID | 错误信息 | 2338| -------- | ---------------------- | 2339| 401 | invalid parameters. | 2340| 17620001 | memory error. | 2341| 17620002 | runtime error. | 2342| 17630001 | crypto operation error. | 2343 2344### init 2345 2346init(pubKey: PubKey): Promise\<void> 2347 2348传入公钥初始化Verify对象,通过Promise获取结果。 2349 2350**系统能力:** SystemCapability.Security.CryptoFramework 2351 2352**参数:** 2353 2354| 参数名 | 类型 | 必填 | 说明 | 2355| ------ | ---- | ---- | ---------------------------- | 2356| pubKey | [PubKey](#pubkey) | 是 | 公钥对象,用于Verify的初始化。 | 2357 2358**返回值:** 2359 2360| 类型 | 说明 | 2361| -------------- | ------------- | 2362| Promise\<void> | Promise对象。 | 2363 2364**错误码:** 2365 2366| 错误码ID | 错误信息 | 2367| -------- | ---------------------- | 2368| 401 | invalid parameters. | 2369| 17620001 | memory error. | 2370| 17620002 | runtime error. | 2371| 17630001 | crypto operation error. | 2372 2373### update 2374 2375update(data: DataBlob, callback: AsyncCallback\<void>): void 2376 2377追加待验签数据,通过注册回调函数完成更新。 2378 2379必须在对[Verify](#verify)实例使用[init()](#init-4)初始化后,才能使用本函数。 2380 2381> **说明:** 2382> 2383> 根据数据量,可以不调用update(即[init](#init-4)完成后直接调用[verify](#verify-1))或多次调用update。<br/> 2384> 算法库目前没有对update(单次或累计)的数据量设置大小限制,建议对于大数据量的验签操作,采用多次update的方式传入数据,避免一次性申请过大内存。<br/> 2385> 验签使用多次update操作的示例代码详见开发指导“[使用签名验签操作](../../security/cryptoFramework-guidelines.md#使用签名验签操作)”。 2386 2387**系统能力:** SystemCapability.Security.CryptoFramework 2388 2389**参数:** 2390 2391| 参数名 | 类型 | 必填 | 说明 | 2392| -------- | --------------------- | ---- | ------------ | 2393| data | [DataBlob](#datablob) | 是 | 传入的消息。 | 2394| callback | AsyncCallback\<void> | 是 | 回调函数。 | 2395 2396**错误码:** 2397 2398| 错误码ID | 错误信息 | 2399| -------- | ---------------------- | 2400| 401 | invalid parameters. | 2401| 17620001 | memory error. | 2402| 17620002 | runtime error. | 2403| 17630001 | crypto operation error. | 2404 2405### update 2406 2407update(data: DataBlob): Promise\<void> 2408 2409追加待验签数据,通过Promise方式完成更新。 2410 2411必须在对[Verify](#verify)实例使用[init()](#init-5)初始化后,才能使用本函数。 2412 2413> **说明:** 2414> 2415> 根据数据量,可以不调用update(即[init](#init-5)完成后直接调用[verify](#verify-2))或多次调用update。<br/> 2416> 算法库目前没有对update(单次或累计)的数据量设置大小限制,建议对于大数据量的验签操作,采用多次update的方式传入数据,避免一次性申请过大内存。<br/> 2417> 验签使用多次update操作的示例代码详见开发指导“[使用签名验签操作](../../security/cryptoFramework-guidelines.md#使用签名验签操作)”。 2418 2419**系统能力:** SystemCapability.Security.CryptoFramework 2420 2421**参数:** 2422 2423| 参数名 | 类型 | 必填 | 说明 | 2424| ------ | -------- | ---- | ---------- | 2425| data | [DataBlob](#datablob) | 是 | 传入的消息。 | 2426 2427**返回值:** 2428 2429| 类型 | 说明 | 2430| -------------- | ------------- | 2431| Promise\<void> | Promise对象。 | 2432 2433**错误码:** 2434 2435| 错误码ID | 错误信息 | 2436| -------- | ---------------------- | 2437| 401 | invalid parameters. | 2438| 17620001 | memory error. | 2439| 17620002 | runtime error. | 2440| 17630001 | crypto operation error. | 2441 2442### verify 2443 2444verify(data: DataBlob | null, signatureData: DataBlob, callback: AsyncCallback\<boolean>): void 2445 2446对数据进行验签,通过注册回调函数返回返回验签结果。 2447 2448**系统能力:** SystemCapability.Security.CryptoFramework 2449 2450**参数:** 2451 2452| 参数名 | 类型 | 必填 | 说明 | 2453| ------------- | -------------------- | ---- | ---------- | 2454| data | [DataBlob](#datablob) \| null<sup>10+</sup> | 是 | 传入的消息。API 10之前只支持DataBlob, API 10之后增加支持null。 | 2455| signatureData | [DataBlob](#datablob) | 是 | 签名数据。 | 2456| callback | AsyncCallback\<boolean> | 是 | 回调函数。 | 2457 2458**错误码:** 2459 2460| 错误码ID | 错误信息 | 2461| -------- | ---------------------- | 2462| 401 | invalid parameters. | 2463| 17620001 | memory error. | 2464| 17620002 | runtime error. | 2465| 17630001 | crypto operation error. | 2466 2467### verify 2468 2469verify(data: DataBlob | null, signatureData: DataBlob): Promise\<boolean> 2470 2471对数据进行验签,通过Promise返回验签结果。 2472 2473**系统能力:** SystemCapability.Security.CryptoFramework 2474 2475**参数:** 2476 2477| 参数名 | 类型 | 必填 | 说明 | 2478| ------------- | -------- | ---- | ---------- | 2479| data | [DataBlob](#datablob) \| null<sup>10+</sup> | 是 | 传入的消息。API 10之前只支持DataBlob, API 10之后增加支持null。 | 2480| signatureData | [DataBlob](#datablob) | 是 | 签名数据。 | 2481 2482**返回值:** 2483 2484| 类型 | 说明 | 2485| ----------------- | ------------------------------ | 2486| Promise\<boolean> | 异步返回值,代表验签是否通过。 | 2487 2488**错误码:** 2489 2490| 错误码ID | 错误信息 | 2491| -------- | ---------------------- | 2492| 401 | invalid parameters. | 2493| 17620001 | memory error. | 2494| 17620002 | runtime error. | 2495| 17630001 | crypto operation error. | 2496 2497**callback示例:** 2498 2499```ts 2500let globalKeyPair: cryptoFramework.KeyPair; // globalKeyPair is an asymmetric key object generated by the asymmetric key generator. The generation process is omitted here. 2501let input1: cryptoFramework.DataBlob; 2502let input2: cryptoFramework.DataBlob; 2503let signMessageBlob: cryptoFramework.DataBlob;// Signed data, which is omitted here. 2504let verifyer = cryptoFramework.createVerify("RSA1024|PKCS1|SHA25"); 2505verifyer.init(globalKeyPair.pubKey, (err, data) => { 2506 verifyer.update(input1, (err, data) => { 2507 verifyer.verify(input2, signMessageBlob, (err, data) => { 2508 console.info("verify result is " + data); 2509 }) 2510 }); 2511}) 2512``` 2513 2514**Promise示例:** 2515 2516```ts 2517let globalKeyPair: cryptoFramework.KeyPair; // globalKeyPair is an asymmetric key object generated by the asymmetric key generator. The generation process is omitted here. 2518let verifyer = cryptoFramework.createVerify("RSA1024|PKCS1|SHA256"); 2519let verifyInitPromise = verifyer.init(globalKeyPair.pubKey); 2520let input1: cryptoFramework.DataBlob;; 2521let input2: cryptoFramework.DataBlob;; 2522let signMessageBlob: cryptoFramework.DataBlob;; // Signed data, which is omitted here. 2523verifyInitPromise.then((): Promise<void> => { 2524 return verifyer.update(input1); 2525}).then(() => { 2526 return verifyer.verify(input2, signMessageBlob); 2527}).then(res => { 2528 console.log("Verify result is " + res); 2529}); 2530``` 2531 2532### setVerifySpec<sup>10+</sup> 2533 2534setVerifySpec(itemType: SignSpecItem, itemValue: number): void 2535 2536设置验签参数。常用的签名参数可以直接通过[createVerify](#cryptoframeworkcreateverify) 来指定,剩余参数可以通过本接口指定。当前只支持RSA算法。 2537 2538验签的参数应当与签名的参数保持一致。 2539 2540**系统能力:** SystemCapability.Security.CryptoFramework 2541 2542**参数:** 2543 2544| 参数名 | 类型 | 必填 | 说明 | 2545| -------- | -------------------- | ---- | ---------- | 2546| itemType | [SignSpecItem](#signspecitem10) | 是 | 用于指定需要设置的验签参数。 | 2547| itemValue | number | 是 | 用于指定验签参数的具体值。 | 2548 2549**错误码:** 2550 2551| 错误码ID | 错误信息 | 2552| -------- | ---------------------- | 2553| 401 | invalid parameters. | 2554| 801 | this operation is not supported. | 2555| 17620001 | memory error. | 2556| 17630001 | crypto operation error. | 2557 2558**示例:** 2559 2560```ts 2561let verifyer: cryptoFramework.Verify; //The process of generating the Verify instance is omitted here. 2562let setN = 20; 2563verifyer.setVerifySpec(cryptoFramework.SignSpecItem.PSS_SALT_LEN_NUM, setN); 2564``` 2565 2566### getVerifySpec<sup>10+</sup> 2567 2568getVerifySpec(itemType: SignSpecItem): string | number 2569 2570获取验签参数。当前只支持RSA算法。 2571 2572验签的参数应当与签名的参数保持一致。 2573 2574**系统能力:** SystemCapability.Security.CryptoFramework 2575 2576**参数:** 2577 2578| 参数名 | 类型 | 必填 | 说明 | 2579| ------ | -------- | ---- | ---------- | 2580| itemType | [SignSpecItem](#signspecitem10) | 是 | 用于指定需要获取的验签参数。 | 2581 2582**返回值:** 2583 2584| 类型 | 说明 | 2585| -------------- | ----------- | 2586| string\|number | 获取的验签参数的具体值。 | 2587 2588**错误码:** 2589 2590| 错误码ID | 错误信息 | 2591| -------- | ---------------------- | 2592| 401 | invalid parameters. | 2593| 801 | this operation is not supported. | 2594| 17620001 | memory error. | 2595| 17630001 | crypto operation error. | 2596 2597**示例:** 2598 2599```ts 2600let verifyer: cryptoFramework.Verify; //The process of generating the Verify instance is omitted here. 2601let saltLen = verifyer.getVerifySpec(cryptoFramework.SignSpecItem.PSS_SALT_LEN_NUM); 2602``` 2603 2604## cryptoFramework.createKeyAgreement 2605 2606createKeyAgreement(algName: string): KeyAgreement 2607 2608KeyAgreement实例生成。 2609 2610支持的规格详见框架概述“[密钥协商规格](../../security/cryptoFramework-overview.md#密钥协商规格)”一节。 2611 2612**系统能力:** SystemCapability.Security.CryptoFramework 2613 2614**参数:** 2615 2616| 参数名 | 类型 | 必填 | 说明 | 2617| ------- | ------ | ---- | --------------------------------- | 2618| algName | string | 是 | 指定密钥协商算法:目前仅支持ECC。 | 2619 2620**返回值**: 2621 2622| 类型 | 说明 | 2623| ------------ | ------------------------------------------ | 2624| KeyAgreement | 返回由输入算法指定生成的KeyAgreement对象。 | 2625 2626**错误码:** 2627 2628| 错误码ID | 错误信息 | 2629| -------- | ---------------------- | 2630| 401 | invalid parameters. | 2631| 801 | this operation is not supported. | 2632| 17620001 | memory error. | 2633 2634**示例:** 2635 2636```ts 2637let keyAgreement = cryptoFramework.createKeyAgreement("ECC256"); 2638 2639``` 2640 2641## KeyAgreement 2642 2643KeyAgreement类,使用密钥协商方法之前需要创建该类的实例进行操作,通过[createKeyAgreement(algName: string): KeyAgreement](#cryptoframeworkcreatekeyagreement)方法构造此实例。 2644 2645### 属性 2646 2647**系统能力:** SystemCapability.Security.CryptoFramework 2648 2649| 名称 | 类型 | 可读 | 可写 | 说明 | 2650| ------- | ------ | ---- | ---- | ---------------------------- | 2651| algName | string | 是 | 否 | 密钥协商指定的算法名称。 | 2652 2653### generateSecret 2654 2655generateSecret(priKey: PriKey, pubKey: PubKey, callback: AsyncCallback\<DataBlob>): void 2656 2657基于传入的私钥与公钥进行密钥协商,通过注册回调函数返回共享秘密。 2658 2659**系统能力:** SystemCapability.Security.CryptoFramework 2660 2661**参数:** 2662 2663| 参数名 | 类型 | 必填 | 说明 | 2664| -------- | ------------------------ | ---- | ---------------------- | 2665| priKey | [PriKey](#prikey) | 是 | 设置密钥协商的私钥输入。 | 2666| pubKey | [PubKey](#pubkey) | 是 | 设置密钥协商的公钥输入。 | 2667| callback | AsyncCallback\<[DataBlob](#datablob)> | 是 | 异步接受共享秘密的回调。 | 2668 2669**错误码:** 2670 2671| 错误码ID | 错误信息 | 2672| -------- | ---------------------- | 2673| 401 | invalid parameters. | 2674| 17620001 | memory error. | 2675| 17620002 | runtime error. | 2676| 17630001 | crypto operation error. | 2677 2678### generateSecret 2679 2680generateSecret(priKey: PriKey, pubKey: PubKey): Promise\<DataBlob> 2681 2682基于传入的私钥与公钥进行密钥协商,通过Promise返回共享秘密。 2683 2684**系统能力:** SystemCapability.Security.CryptoFramework 2685 2686**参数:** 2687 2688| 参数名 | 类型 | 必填 | 说明 | 2689| ------ | ------ | ---- | ---------------------- | 2690| priKey | [PriKey](#prikey) | 是 | 设置密钥协商的私钥输入。 | 2691| pubKey | [PubKey](#pubkey) | 是 | 设置密钥协商的公钥输入。 | 2692 2693**返回值:** 2694 2695| 类型 | 说明 | 2696| ------------------ | -------- | 2697| Promise\<[DataBlob](#datablob)> | 共享秘密。 | 2698 2699**错误码:** 2700 2701| 错误码ID | 错误信息 | 2702| -------- | ---------------------- | 2703| 401 | invalid parameters. | 2704| 17620001 | memory error. | 2705| 17620002 | runtime error. | 2706| 17630001 | crypto operation error. | 2707 2708**callback示例:** 2709 2710```ts 2711import { BusinessError } from '@ohos.base'; 2712 2713let globalKeyPair: cryptoFramework.KeyPair; // 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, (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示例:** 2725 2726```ts 2727import { BusinessError } from '@ohos.base'; 2728 2729let globalKeyPair: cryptoFramework.KeyPair; // 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: BusinessError) => { 2735 console.error("keyAgreement error."); 2736}); 2737``` 2738 2739## cryptoFramework.createMd 2740 2741createMd(algName: string): Md 2742 2743生成Md实例,用于进行消息摘要的计算与操作。 2744 2745支持的规格详见框架概述“[MD消息摘要算法规格](../../security/cryptoFramework-overview.md#md消息摘要算法规格)”一节。 2746 2747**系统能力:** SystemCapability.Security.CryptoFramework 2748 2749**参数:** 2750 2751| 参数名 | 类型 | 必填 | 说明 | 2752| ------- | ------ | ---- | ------------------------------------------------------------ | 2753| algName | string | 是 | 指定摘要算法,支持算法请参考“[MD算法支持范围](../../security/cryptoFramework-overview.md#md消息摘要算法规格)”一节。 | 2754 2755**返回值**: 2756 2757| 类型 | 说明 | 2758| ---- | --------------------------------------- | 2759| Md | 返回由输入算法指定生成的[Md](#md)对象。 | 2760 2761**错误码:** 2762 2763| 错误码ID | 错误信息 | 2764| -------- | ------------------ | 2765| 401 | invalid parameters. | 2766| 17620001 | memory error. | 2767 2768**示例:** 2769 2770```ts 2771import { BusinessError } from '@ohos.base'; 2772 2773try { 2774 // Set algName based on the algorithm supported. 2775 let md = cryptoFramework.createMd("SHA256"); 2776} catch (error) { 2777 let e: BusinessError = error as BusinessError; 2778 console.error(`sync error, ${e.code}, ${e.message}`); 2779} 2780``` 2781 2782## Md 2783 2784Md类,调用Md方法可以进行MD(Message Digest)摘要计算。调用前,需要通过[createMd](#cryptoframeworkcreatemd)构造Md实例。 2785 2786### 属性 2787 2788**系统能力:** SystemCapability.Security.CryptoFramework 2789 2790| 名称 | 类型 | 可读 | 可写 | 说明 | 2791| ------- | ------ | ---- | ---- | ---------------------- | 2792| algName | string | 是 | 否 | 代表指定的摘要算法名。 | 2793 2794### update 2795 2796update(input: DataBlob, callback: AsyncCallback\<void>): void 2797 2798传入消息进行Md更新计算,通过注册回调函数更新。 2799 2800> **说明:** 2801> 2802> Md算法多次调用update更新的代码示例详见开发指导“[使用摘要操作](../../security/cryptoFramework-guidelines.md#使用摘要操作)”。 2803 2804**系统能力:** SystemCapability.Security.CryptoFramework 2805 2806**参数:** 2807 2808| 参数名 | 类型 | 必填 | 说明 | 2809| -------- | --------------------- | ---- | ------------ | 2810| input | [DataBlob](#datablob) | 是 | 传入的消息。 | 2811| callback | AsyncCallback\<void> | 是 | 回调函数。 | 2812 2813**错误码:** 2814 2815| 错误码ID | 错误信息 | 2816| -------- | ---------------------- | 2817| 401 | invalid parameters. | 2818| 17630001 | crypto operation error. | 2819 2820**示例:** 2821 2822```ts 2823import { BusinessError } from '@ohos.base'; 2824 2825let md = cryptoFramework.createMd("SHA256"); 2826console.info("Md algName is: " + md.algName); 2827 2828let blob: cryptoFramework.DataBlob; 2829md.update(blob, (err,) => { 2830 if (err) { 2831 console.error("[Callback] err: " + err.code); 2832 } 2833}); 2834``` 2835 2836### update 2837 2838update(input: DataBlob): Promise\<void> 2839 2840传入消息进行Md更新计算,通过Promise更新。 2841 2842> **说明:** 2843> 2844> Md算法多次调用update更新的代码示例详见开发指导“[使用摘要操作](../../security/cryptoFramework-guidelines.md#使用摘要操作)”。 2845 2846**系统能力:** SystemCapability.Security.CryptoFramework 2847 2848| 参数名 | 类型 | 必填 | 说明 | 2849| ------ | -------- | ---- | ------------ | 2850| input | DataBlob | 是 | 传入的消息。 | 2851 2852**返回值:** 2853 2854| 类型 | 说明 | 2855| -------------- | ------------- | 2856| Promise\<void> | Promise对象。 | 2857 2858**错误码:** 2859 2860| 错误码ID | 错误信息 | 2861| -------- | ---------------------- | 2862| 401 | invalid parameters. | 2863| 17630001 | crypto operation error. | 2864 2865**示例:** 2866 2867```ts 2868import { BusinessError } from '@ohos.base'; 2869 2870let md = cryptoFramework.createMd("SHA256"); 2871console.info("Md algName is: " + md.algName); 2872 2873let blob: cryptoFramework.DataBlob; 2874let promiseMdUpdate = md.update(blob); 2875promiseMdUpdate.then(() => { 2876 // do something 2877}).catch((error: BusinessError) => { 2878 console.error("[Promise]: error: " + error.message); 2879}); 2880``` 2881 2882### digest 2883 2884digest(callback: AsyncCallback\<DataBlob>): void 2885 2886通过注册回调函数返回Md的计算结果。 2887 2888**系统能力:** SystemCapability.Security.CryptoFramework 2889 2890| 参数名 | 类型 | 必填 | 说明 | 2891| -------- | ------------------------ | ---- | ---------- | 2892| callback | AsyncCallback\<DataBlob> | 是 | 回调函数。 | 2893 2894**错误码:** 2895 2896| 错误码ID | 错误信息 | 2897| -------- | ---------------------- | 2898| 17620001 | memory error. | 2899| 17630001 | crypto operation error. | 2900 2901**示例:** 2902 2903```ts 2904import { BusinessError } from '@ohos.base'; 2905 2906let md = cryptoFramework.createMd("SHA256"); 2907console.info("Md algName is: " + md.algName); 2908 2909let blob: cryptoFramework.DataBlob; 2910md.update(blob, (err,) => { 2911 if (err) { 2912 console.error("[Callback] err: " + err.code); 2913 } 2914 md.digest((err1, mdOutput) => { 2915 if (err1) { 2916 console.error("[Callback] err: " + err1.code); 2917 } else { 2918 console.error("[Callback]: MD result: " + mdOutput); 2919 } 2920 }); 2921}); 2922``` 2923 2924### digest 2925 2926digest(): Promise\<DataBlob> 2927 2928通过Promise返回Md的计算结果。 2929 2930**系统能力:** SystemCapability.Security.CryptoFramework 2931 2932**返回值:** 2933 2934| 类型 | 说明 | 2935| ------------------ | ----------- | 2936| Promise\<[DataBlob](#datablob)> | Promise对象。 | 2937 2938**错误码:** 2939 2940| 错误码ID | 错误信息 | 2941| -------- | ---------------------- | 2942| 17620001 | memory error. | 2943| 17630001 | crypto operation error. | 2944 2945**示例:** 2946 2947```ts 2948import { BusinessError } from '@ohos.base'; 2949 2950let md = cryptoFramework.createMd("SHA256"); 2951console.info("Md algName is: " + md.algName); 2952 2953let blob: cryptoFramework.DataBlob; 2954let promiseMdUpdate = md.update(blob); 2955promiseMdUpdate.then(() => { 2956 let promiseMdDigest = md.digest(); 2957 return promiseMdDigest; 2958}).then(mdOutput => { 2959 console.error("[Promise]: MD result: " + mdOutput.data); 2960}).catch((error: BusinessError) => { 2961 console.error("[Promise]: error: " + error.message); 2962}); 2963``` 2964 2965### getMdLength 2966 2967getMdLength(): number 2968 2969获取Md消息摘要长度(字节数)。 2970 2971**系统能力:** SystemCapability.Security.CryptoFramework 2972 2973**返回值:** 2974 2975| 类型 | 说明 | 2976| ------ | -------------------------- | 2977| number | 返回md计算结果的字节长度。 | 2978 2979**错误码:** 2980 2981| 错误码ID | 错误信息 | 2982| -------- | ---------------------- | 2983| 17630001 | crypto operation error. | 2984 2985**示例:** 2986 2987```ts 2988import { BusinessError } from '@ohos.base'; 2989 2990let md = cryptoFramework.createMd("SHA256"); 2991console.info("Md algName is: " + md.algName); 2992 2993let blob: cryptoFramework.DataBlob; 2994let promiseMdUpdate = md.update(blob); 2995promiseMdUpdate.then(() => { 2996 let promiseMdDigest = md.digest(); 2997 return promiseMdDigest; 2998}).then(mdOutput => { 2999 console.error("[Promise]: MD result: " + mdOutput.data); 3000 let mdLen = md.getMdLength(); 3001 console.error("MD len: " + mdLen); 3002}).catch((error: BusinessError) => { 3003 console.error("[Promise]: error: " + error.message); 3004}); 3005``` 3006 3007## cryptoFramework.createMac 3008 3009createMac(algName: string): Mac 3010 3011生成Mac实例,用于进行消息认证码的计算与操作。 3012 3013支持的规格详见框架概述“[HMAC消息认证码算法规格](../../security/cryptoFramework-overview.md#hmac消息认证码算法规格)”一节。 3014 3015**系统能力:** SystemCapability.Security.CryptoFramework 3016 3017**参数:** 3018 3019| 参数名 | 类型 | 必填 | 说明 | 3020| ------- | ------ | ---- | ------------------------------------------------------------ | 3021| algName | string | 是 | 指定摘要算法,支持算法请参考“[HMAC算法支持范围](../../security/cryptoFramework-overview.md#hmac消息认证码算法规格)”一节。 | 3022 3023**返回值**: 3024 3025| 类型 | 说明 | 3026| ---- | ----------------------------------------- | 3027| Mac | 返回由输入算法指定生成的[Mac](#mac)对象。 | 3028 3029**错误码:** 3030 3031| 错误码ID | 错误信息 | 3032| -------- | ------------------ | 3033| 401 | invalid parameters. | 3034| 17620001 | memory error. | 3035 3036**示例:** 3037 3038```ts 3039import { BusinessError } from '@ohos.base'; 3040 3041try { 3042 // Set algName based on the algorithm supported. 3043 let mac = cryptoFramework.createMac("SHA256"); 3044} catch (error) { 3045 let e: BusinessError = error as BusinessError; 3046 console.error(`sync error, ${e.code}, ${e.message}`); 3047} 3048``` 3049 3050## Mac 3051 3052Mac类,调用Mac方法可以进行MAC(Message Authentication Code)加密计算。调用前,需要通过[createMac](#cryptoframeworkcreatemac)构造Mac实例。 3053 3054### 属性 3055 3056**系统能力:** SystemCapability.Security.CryptoFramework 3057 3058| 名称 | 类型 | 可读 | 可写 | 说明 | 3059| ------- | ------ | ---- | ---- | ---------------------- | 3060| algName | string | 是 | 否 | 代表指定的摘要算法名。 | 3061 3062### init 3063 3064init(key: SymKey, callback: AsyncCallback\<void>): void 3065 3066使用对称密钥初始化Mac计算,通过注册回调函数获取结果。 3067 3068**系统能力:** SystemCapability.Security.CryptoFramework 3069 3070**参数:** 3071 3072| 参数名 | 类型 | 必填 | 说明 | 3073| -------- | -------------------- | ---- | -------------- | 3074| key | [SymKey](#symkey) | 是 | 共享对称密钥。 | 3075| callback | AsyncCallback\<void> | 是 | 回调函数。 | 3076 3077**错误码:** 3078 3079| 错误码ID | 错误信息 | 3080| -------- | ---------------------- | 3081| 401 | invalid parameters. | 3082| 17630001 | crypto operation error. | 3083 3084**示例:** 3085 3086```ts 3087import { BusinessError } from '@ohos.base'; 3088 3089let mac = cryptoFramework.createMac("SHA256"); 3090let keyBlob: cryptoFramework.DataBlob; 3091let symKeyGenerator = cryptoFramework.createSymKeyGenerator("AES128"); 3092symKeyGenerator.convertKey(keyBlob, (err, symKey) => { 3093 if (err) { 3094 console.error("[Callback] err: " + err.code); 3095 } 3096 mac.init(symKey, (err1, ) => { 3097 if (err1) { 3098 console.error("[Callback] err: " + err1.code); 3099 } 3100 }); 3101}); 3102``` 3103 3104### init 3105 3106init(key: SymKey): Promise\<void> 3107 3108使用对称密钥初始化Mac计算,通过Promise获取结果。 3109 3110**系统能力:** SystemCapability.Security.CryptoFramework 3111 3112**参数:** 3113 3114| 参数名 | 类型 | 必填 | 说明 | 3115| ------ | ------ | ---- | ------------ | 3116| key | [SymKey](#symkey) | 是 | 共享对称密钥。 | 3117 3118**返回值:** 3119 3120| 类型 | 说明 | 3121| -------------- | ------------- | 3122| Promise\<void> | Promise对象。 | 3123 3124**错误码:** 3125 3126| 错误码ID | 错误信息 | 3127| -------- | ---------------------- | 3128| 401 | invalid parameters. | 3129| 17630001 | crypto operation error. | 3130 3131**示例:** 3132 3133```ts 3134import { BusinessError } from '@ohos.base'; 3135 3136let mac = cryptoFramework.createMac("SHA256"); 3137console.info("Mac algName is: " + mac.algName); 3138 3139let keyBlob: cryptoFramework.DataBlob; 3140let symKeyGenerator = cryptoFramework.createSymKeyGenerator("AES128"); 3141let promiseConvertKey = symKeyGenerator.convertKey(keyBlob); 3142promiseConvertKey.then(symKey => { 3143 let promiseMacInit = mac.init(symKey); 3144 return promiseMacInit; 3145}).catch((error: BusinessError) => { 3146 console.error("[Promise]: error: " + error.message); 3147}); 3148 3149``` 3150 3151### update 3152 3153update(input: DataBlob, callback: AsyncCallback\<void>): void 3154 3155传入消息进行Mac更新计算,通过注册回调函数获取结果。 3156 3157> **说明:** 3158> 3159> Hmac算法多次调用update更新的代码示例详见开发指导“[使用消息认证码操作](../../security/cryptoFramework-guidelines.md#使用消息认证码操作)”。 3160 3161**系统能力:** SystemCapability.Security.CryptoFramework 3162 3163**参数:** 3164 3165| 参数名 | 类型 | 必填 | 说明 | 3166| -------- | --------------------- | ---- | ------------ | 3167| input | [DataBlob](#datablob) | 是 | 传入的消息。 | 3168| callback | AsyncCallback\<void> | 是 | 回调函数。 | 3169 3170**错误码:** 3171 3172| 错误码ID | 错误信息 | 3173| -------- | ---------------------- | 3174| 401 | invalid parameters. | 3175| 17630001 | crypto operation error. | 3176 3177**示例:** 3178 3179```ts 3180import { BusinessError } from '@ohos.base'; 3181 3182let keyBlob: cryptoFramework.DataBlob; 3183let mac = cryptoFramework.createMac("SHA256"); 3184let symKeyGenerator = cryptoFramework.createSymKeyGenerator("AES128"); 3185symKeyGenerator.convertKey(keyBlob, (err, symKey) => { 3186 if (err) { 3187 console.error("[Callback] err: " + err.code); 3188 } 3189 mac.init(symKey, (err1, ) => { 3190 if (err1) { 3191 console.error("[Callback] err: " + err1.code); 3192 } 3193 let blob: cryptoFramework.DataBlob; 3194 mac.update(blob, (err2, data) => { 3195 if (err2) { 3196 console.error("[Callback] err: " + err2.code); 3197 } 3198 }); 3199 }); 3200}); 3201``` 3202 3203### update 3204 3205update(input: DataBlob): Promise\<void> 3206 3207传入消息进行Mac更新计算,通过Promise获取结果。 3208 3209> **说明:** 3210> 3211> Hmac算法多次调用update更新的代码示例详见开发指导“[使用消息认证码操作](../../security/cryptoFramework-guidelines.md#使用消息认证码操作)”。 3212 3213**系统能力:** SystemCapability.Security.CryptoFramework 3214 3215**参数:** 3216 3217| 参数名 | 类型 | 必填 | 说明 | 3218| ------ | -------- | ---- | ---------- | 3219| input | [DataBlob](#datablob) | 是 | 传入的消息。 | 3220 3221**返回值:** 3222 3223| 类型 | 说明 | 3224| -------------- | ------------- | 3225| Promise\<void> | Promise对象。 | 3226 3227**错误码:** 3228 3229| 错误码ID | 错误信息 | 3230| -------- | ---------------------- | 3231| 401 | invalid parameters. | 3232| 17630001 | crypto operation error. | 3233 3234**示例:** 3235 3236```ts 3237import { BusinessError } from '@ohos.base'; 3238 3239let mac = cryptoFramework.createMac("SHA256"); 3240console.info("Mac algName is: " + mac.algName); 3241 3242let keyBlob: cryptoFramework.DataBlob; 3243let symKeyGenerator = cryptoFramework.createSymKeyGenerator("AES128"); 3244let promiseConvertKey = symKeyGenerator.convertKey(keyBlob); 3245promiseConvertKey.then(symKey => { 3246 let promiseMacInit = mac.init(symKey); 3247 return promiseMacInit; 3248}).then(() => { 3249 let blob: cryptoFramework.DataBlob; 3250 let promiseMacUpdate = mac.update(blob); 3251 return promiseMacUpdate; 3252}).catch((error: BusinessError) => { 3253 console.error("[Promise]: error: " + error.message); 3254}); 3255 3256``` 3257 3258### doFinal 3259 3260doFinal(callback: AsyncCallback\<DataBlob>): void 3261 3262通过注册回调函数返回Mac的计算结果。 3263 3264**系统能力:** SystemCapability.Security.CryptoFramework 3265 3266**参数:** 3267 3268| 参数名 | 类型 | 必填 | 说明 | 3269| -------- | ------------------------ | ---- | -------- | 3270| callback | AsyncCallback\<[DataBlob](#datablob)> | 是 | 回调函数。 | 3271 3272**错误码:** 3273 3274| 错误码ID | 错误信息 | 3275| -------- | ---------------------- | 3276| 17620001 | memory error. | 3277| 17630001 | crypto operation error. | 3278 3279**示例:** 3280 3281```ts 3282import { BusinessError } from '@ohos.base'; 3283 3284let keyBlob: cryptoFramework.DataBlob; 3285let mac = cryptoFramework.createMac("SHA256"); 3286let symKeyGenerator = cryptoFramework.createSymKeyGenerator("AES128"); 3287symKeyGenerator.convertKey(keyBlob, (err, symKey) => { 3288 if (err) { 3289 console.error("[Callback] err: " + err.code); 3290 } 3291 mac.init(symKey, (err1, ) => { 3292 if (err1) { 3293 console.error("[Callback] err: " + err1.code); 3294 } 3295 let blob: cryptoFramework.DataBlob; 3296 mac.update(blob, (err2, ) => { 3297 if (err2) { 3298 console.error("[Callback] err: " + err2.code); 3299 } 3300 mac.doFinal((err3, macOutput) => { 3301 if (err3) { 3302 console.error("[Callback] err: " + err3.code); 3303 } else { 3304 console.error("[Promise]: HMAC result: " + macOutput); 3305 } 3306 }); 3307 }); 3308 }); 3309}); 3310``` 3311 3312### doFinal 3313 3314doFinal(): Promise\<DataBlob> 3315 3316通过Promise返回Mac的计算结果。 3317 3318**系统能力:** SystemCapability.Security.CryptoFramework 3319 3320**返回值:** 3321 3322| 类型 | 说明 | 3323| ------------------ | ----------- | 3324| Promise\<[DataBlob](#datablob)> | Promise对象。 | 3325 3326**错误码:** 3327 3328| 错误码ID | 错误信息 | 3329| -------- | ---------------------- | 3330| 17620001 | memory error. | 3331| 17630001 | crypto operation error. | 3332 3333**示例:** 3334 3335```ts 3336import { BusinessError } from '@ohos.base'; 3337 3338let mac = cryptoFramework.createMac("SHA256"); 3339console.info("Mac algName is: " + mac.algName); 3340let keyBlob: cryptoFramework.DataBlob; 3341let symKeyGenerator = cryptoFramework.createSymKeyGenerator("AES128"); 3342let promiseConvertKey = symKeyGenerator.convertKey(keyBlob); 3343promiseConvertKey.then(symKey => { 3344 let promiseMacInit = mac.init(symKey); 3345 return promiseMacInit; 3346}).then(() => { 3347 let blob: cryptoFramework.DataBlob; 3348 let promiseMacUpdate = mac.update(blob); 3349 return promiseMacUpdate; 3350}).then(() => { 3351 let promiseMacDoFinal = mac.doFinal(); 3352 return promiseMacDoFinal; 3353}).then(macOutput => { 3354 console.error("[Promise]: HMAC result: " + macOutput.data); 3355}).catch((error: BusinessError) => { 3356 console.error("[Promise]: error: " + error.message); 3357}); 3358``` 3359 3360### getMacLength 3361 3362getMacLength(): number 3363 3364获取Mac消息认证码的长度(字节数)。 3365 3366**系统能力:** SystemCapability.Security.CryptoFramework 3367 3368**返回值:** 3369 3370| 类型 | 说明 | 3371| ------ | --------------------------- | 3372| number | 返回mac计算结果的字节长度。 | 3373 3374**错误码:** 3375 3376| 错误码ID | 错误信息 | 3377| -------- | ---------------------- | 3378| 17630001 | crypto operation error. | 3379 3380**示例:** 3381 3382```ts 3383import { BusinessError } from '@ohos.base'; 3384 3385let mac = cryptoFramework.createMac("SHA256"); 3386console.info("Mac algName is: " + mac.algName); 3387let keyBlob: cryptoFramework.DataBlob; 3388let symKeyGenerator = cryptoFramework.createSymKeyGenerator("AES128"); 3389let promiseConvertKey = symKeyGenerator.convertKey(keyBlob); 3390promiseConvertKey.then(symKey => { 3391 let promiseMacInit = mac.init(symKey); 3392 return promiseMacInit; 3393}).then(() => { 3394 let blob: cryptoFramework.DataBlob; 3395 let promiseMacUpdate = mac.update(blob); 3396 return promiseMacUpdate; 3397}).then(() => { 3398 let promiseMacDoFinal = mac.doFinal(); 3399 return promiseMacDoFinal; 3400}).then(macOutput => { 3401 console.error("[Promise]: HMAC result: " + macOutput.data); 3402 let macLen = mac.getMacLength(); 3403 console.error("MAC len: " + macLen); 3404}).catch((error: BusinessError) => { 3405 console.error("[Promise]: error: " + error.message); 3406}); 3407``` 3408 3409## cryptoFramework.createRandom 3410 3411createRandom(): Random 3412 3413生成Random实例,用于进行随机数的计算与设置种子。 3414 3415支持的规格详见框架概述“[随机数算法规格](../../security/cryptoFramework-overview.md#随机数)”一节。 3416 3417**系统能力:** SystemCapability.Security.CryptoFramework 3418 3419**返回值**: 3420 3421| 类型 | 说明 | 3422| ------ | ----------------------------------------------- | 3423| Random | 返回由输入算法指定生成的[Random](#random)对象。 | 3424 3425**错误码:** 3426 3427| 错误码ID | 错误信息 | 3428| -------- | ------------ | 3429| 17620001 | memory error. | 3430 3431**示例:** 3432 3433```ts 3434import { BusinessError } from '@ohos.base'; 3435 3436try { 3437 let rand = cryptoFramework.createRandom(); 3438} catch (error) { 3439 let e: BusinessError = error as BusinessError; 3440 console.error(`sync error, ${e.code}, ${e.message}`); 3441} 3442``` 3443 3444## Random 3445 3446Random类,调用Random方法可以进行随机数计算。调用前,需要通过[createRandom](#cryptoframeworkcreaterandom)构造Random实例。 3447 3448### 属性 3449 3450**系统能力:** SystemCapability.Security.CryptoFramework 3451 3452| 名称 | 类型 | 可读 | 可写 | 说明 | 3453| ------- | ------ | ---- | ---- | -------------------- | 3454| algName<sup>10+</sup> | string | 是 | 否 | 代表当前使用的随机数生成算法,目前只支持“CTR_DRBG"。 | 3455 3456### generateRandom 3457 3458generateRandom(len: number, callback: AsyncCallback\<DataBlob>): void 3459 3460异步生成指定长度的随机数,通过注册回调函数返回。 3461 3462**系统能力:** SystemCapability.Security.CryptoFramework 3463 3464**参数:** 3465 3466| 参数名 | 类型 | 必填 | 说明 | 3467| -------- | ------------------------ | ---- | -------------------- | 3468| len | number | 是 | 表示生成随机数的长度,单位为byte,范围在[1, INT_MAX]。 | 3469| callback | AsyncCallback\<[DataBlob](#datablob)> | 是 | 回调函数。 | 3470 3471**错误码:** 3472 3473| 错误码ID | 错误信息 | 3474| -------- | ---------------------- | 3475| 401 | invalid parameters. | 3476| 17620001 | memory error. | 3477| 17630001 | crypto operation error. | 3478 3479**示例:** 3480 3481```ts 3482import { BusinessError } from '@ohos.base'; 3483 3484let rand = cryptoFramework.createRandom(); 3485rand.generateRandom(12, (err, randData) => { 3486 if (err) { 3487 console.error("[Callback] err: " + err.code); 3488 } else { 3489 console.error("[Callback]: generate random result: " + randData.data); 3490 } 3491}); 3492``` 3493 3494### generateRandom 3495 3496generateRandom(len: number): Promise\<DataBlob> 3497 3498异步生成指定长度的随机数,通过Promise返回。 3499 3500**系统能力:** SystemCapability.Security.CryptoFramework 3501 3502**参数:** 3503 3504| 参数名 | 类型 | 必填 | 说明 | 3505| ------ | ------ | ---- | ------------------------------------------------------ | 3506| len | number | 是 | 表示生成随机数的长度,单位为byte,范围在[1, INT_MAX]。 | 3507 3508**返回值:** 3509 3510| 类型 | 说明 | 3511| ------------------ | ----------- | 3512| Promise\<[DataBlob](#datablob)> | Promise对象。 | 3513 3514**错误码:** 3515 3516| 错误码ID | 错误信息 | 3517| -------- | ---------------------- | 3518| 401 | invalid parameters. | 3519| 17620001 | memory error. | 3520| 17630001 | crypto operation error. | 3521 3522**示例:** 3523 3524```ts 3525import { BusinessError } from '@ohos.base'; 3526 3527let rand = cryptoFramework.createRandom(); 3528let promiseGenerateRand = rand.generateRandom(12); 3529promiseGenerateRand.then(randData => { 3530 console.error("[Promise]: rand result: " + randData.data); 3531}).catch((error: BusinessError) => { 3532 console.error("[Promise]: error: " + error.message); 3533}); 3534``` 3535 3536### generateRandomSync<sup>10+</sup> 3537 3538generateRandomSync(len: number): DataBlob 3539 3540同步生成指定长度的随机数。 3541 3542**系统能力:** SystemCapability.Security.CryptoFramework 3543 3544**参数:** 3545 3546| 参数名 | 类型 | 必填 | 说明 | 3547| ------ | ------ | ---- | -------------------- | 3548| len | number | 是 | 表示生成随机数的长度,单位为byte,范围在[1, INT_MAX]。 | 3549 3550**返回值:** 3551 3552| 类型 | 说明 | 3553| ------------------ | ----------- | 3554|[DataBlob](#datablob) | 表示生成的随机数。 | 3555 3556**错误码:** 3557 3558| 错误码ID | 错误信息 | 3559| -------- | ---------------------- | 3560| 401 | invalid parameters. | 3561| 17620001 | memory error. | 3562| 17630001 | crypto operation error. | 3563 3564**示例:** 3565 3566```ts 3567import { BusinessError } from '@ohos.base'; 3568 3569let rand = cryptoFramework.createRandom(); 3570try { 3571 let randData = rand.generateRandomSync(12); 3572 if (randData != null) { 3573 console.info("[Sync]: rand result: " + randData.data); 3574 } else { 3575 console.error("[Sync]: get rand result fail!"); 3576 } 3577} catch (error) { 3578 let e: BusinessError = error as BusinessError; 3579 console.error(`sync error, ${e.code}, ${e.message}`); 3580} 3581``` 3582 3583### setSeed 3584 3585setSeed(seed: DataBlob): void 3586 3587设置指定的种子。 3588 3589**系统能力:** SystemCapability.Security.CryptoFramework 3590 3591| 参数名 | 类型 | 必填 | 说明 | 3592| ------ | -------- | ---- | ------------ | 3593| seed | DataBlob | 是 | 设置的种子。 | 3594 3595**错误码:** 3596 3597| 错误码ID | 错误信息 | 3598| -------- | ----------------- | 3599| 17620001 | memory error. | 3600 3601**示例:** 3602 3603```ts 3604import { BusinessError } from '@ohos.base'; 3605 3606let rand = cryptoFramework.createRandom(); 3607rand.generateRandom(12, (err, randData) => { 3608 if (err) { 3609 console.error("[Callback] err: " + err.code); 3610 } else { 3611 console.info("[Callback]: generate random result: " + randData.data); 3612 try { 3613 rand.setSeed(randData); 3614 } catch (error) { 3615 let e: BusinessError = error as BusinessError; 3616 console.error(`sync error, ${e.code}, ${e.message}`); 3617 } 3618 } 3619}); 3620``` 3621