• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Generating an Asymmetric Key Pair Based on Key Parameters
2
3This topic uses RSA and ECC as an example to describe how to generate an asymmetric key pair (**KeyPair**) based on the specified key parameters and obtain the key parameter properties.
4
5The **KeyPair** object created can be used for subsequent operations, such as encryption and decryption. The obtained key parameter properties can be used for key storage and transfer.
6
7
8## Generating an RSA Public Key Based on Key Parameters
9
10For details about the algorithm specifications, see [RSA](crypto-asym-key-generation-conversion-spec.md#rsa).
11
121. Create an [RSACommonParamsSpec](../../reference/apis-crypto-architecture-kit/js-apis-cryptoFramework.md#rsacommonparamsspec10) object to specify the common parameter (**n**) of both the public and private keys of the RSA algorithm.
13
14   **RSACommonParamsSpec** is a child class of **AsyKeySpec**. Specify the RSA algorithm in the **algName** parameter, and set the key parameter type to **AsyKeySpecType.COMMON_PARAMS_SPEC**, which indicates the common parameter for both the public and private keys.
15
16   When key parameters are specified for generating a key, the bigint value must be a positive number in big-endian format.
17
182. Create an [RSAPubKeySpec](../../reference/apis-crypto-architecture-kit/js-apis-cryptoFramework.md#rsapubkeyspec10) object to specify the parameters (**n**, **pk**) contained in the public key of the RSA algorithm.
19
20   **RSAPubKeySpec** is a child class of **AsyKeySpec**. Specify the RSA algorithm in the **algName** parameter, and set the key parameter type to **AsyKeySpecType.PUBLIC_KEY_SPEC**, which indicates the parameters of the public key.
21
223. Use [cryptoFramework.createAsyKeyGeneratorBySpec](../../reference/apis-crypto-architecture-kit/js-apis-cryptoFramework.md#cryptoframeworkcreateasykeygeneratorbyspec10) with the **RSAPubKeySpec** object to create an asymmetric key generator (**AsyKeyGeneratorBySpec**) object.
23
244. Use [AsyKeyGeneratorBySpec.generatePubKey](../../reference/apis-crypto-architecture-kit/js-apis-cryptoFramework.md#generatepubkey-1) to generate the public key (**PubKey**).
25
265. Use [PubKey.getAsyKeySpec](../../reference/apis-crypto-architecture-kit/js-apis-cryptoFramework.md#getasykeyspec10) to obtain the modulus **n** and the public key exponent **pk** (expressed as e in the formula).
27
28- Example: Generate an RSA public key based on key parameters (using callback-based APIs).
29  ```ts
30  import cryptoFramework from '@ohos.security.cryptoFramework';
31  // Generate an RSA public key parameter (RsaPubKeySpec).
32  function genRsaPubKeySpec(nIn: bigint, eIn: bigint): cryptoFramework.RSAPubKeySpec {
33    let rsaCommSpec: cryptoFramework.RSACommonParamsSpec = {
34      n: nIn,
35      algName: 'RSA',
36      specType: cryptoFramework.AsyKeySpecType.COMMON_PARAMS_SPEC
37    };
38    let rsaPubKeySpec: cryptoFramework.RSAPubKeySpec = {
39      params: rsaCommSpec,
40      pk: eIn,
41      algName: 'RSA',
42      specType: cryptoFramework.AsyKeySpecType.PUBLIC_KEY_SPEC
43    };
44    return rsaPubKeySpec;
45  }
46  // Construct an RSA public key specification object based on the key parameter.
47  function genRsa2048PubKeySpec() {
48    let nIn = BigInt('0x9260d0750ae117eee55c3f3deaba74917521a262ee76007cdf8a56755ad73a1598a1408410a01434c3f5bc54a88b57fa19fc4328daea0750a4c44e88cff3b2382621b80f670464433e4336e6d003e8cd65bff211da144b88291c2259a00a72b711c116ef7686e8fee34e4d933c868187bdc26f7be071493c86f7a5941c3510806ad67b0f94d88f5cf5c02a092821d8626e8932b65c5bd8c92049c210932b7afa7ac59c0e886ae5c1edb00d8ce2c57633db26bd6639bff73cee82be9275c402b4cf2a4388da8cf8c64eefe1c5a0f5ab8057c39fa5c0589c3e253f0960332300f94bea44877b588e1edbde97cf2360727a09b775262d7ee552b3319b9266f05a25');
49    let eIn = BigInt('0x010001');
50    return genRsaPubKeySpec(nIn, eIn);
51  }
52  // Compare the RSA public key specifications with the expected value.
53  function compareRsaPubKeyBySpec(rsaKeySpec: cryptoFramework.RSAPubKeySpec, n: bigint | string | number, e: bigint | string | number) {
54    if (typeof n === 'string' || typeof e === 'string') {
55      console.error('type is string');
56      return false;
57    }
58    if (typeof n === 'number' || typeof e === 'number') {
59      console.error('type is number');
60      return false;
61    }
62    if (rsaKeySpec.params.n != n) {
63      return false;
64    }
65    if (rsaKeySpec.pk != e) {
66      return false;
67    }
68    return true;
69  }
70  // Generate an RSA public key based on the RSA public key specifications, obtain the key specifications, and compare it with the expected value.
71  function rsaUsePubKeySpecGetCallback() {
72    let rsaPubKeySpec = genRsa2048PubKeySpec();
73    let rsaGeneratorSpec = cryptoFramework.createAsyKeyGeneratorBySpec(rsaPubKeySpec);
74    rsaGeneratorSpec.generatePubKey((error, key) => {
75      let pubKey = key;
76      let nBN = pubKey.getAsyKeySpec(cryptoFramework.AsyKeySpecItem.RSA_N_BN);
77      let eBN = pubKey.getAsyKeySpec(cryptoFramework.AsyKeySpecItem.RSA_PK_BN);
78      if (compareRsaPubKeyBySpec(rsaPubKeySpec, nBN, eBN) != true) {
79        AlertDialog.show({ message: 'error pub key big number' });
80      } else {
81        console.info('n, e in the pubKey are same as the spec.');
82      }
83      if (error) {
84        console.error('generate pubKey error' + 'error code: ' + error.code + 'error message' + error.message);
85      }
86    });
87  }
88  ```
89
90
91
92## Generating an ECC Key Pair Based on Key Parameters
93
94For details about the algorithm specifications, see [ECC](crypto-asym-key-generation-conversion-spec.md#ecc).
95
961. Create an [ECCCommonParamsSpec](../../reference/apis-crypto-architecture-kit/js-apis-cryptoFramework.md#ecccommonparamsspec10) object to specify the common parameters of both the public and private keys of the ECC algorithm.
97   **ECCCommonParamsSpec** is a child class of **AsyKeySpec**. Specify the ECC algorithm in the **algName** parameter, and set the key parameter type to **AsyKeySpecType.COMMON_PARAMS_SPEC**, which indicates the common parameter for both the public and private keys.
98
99   When key parameters are specified for generating a key, the bigint value must be a positive number in big-endian format.
100
1012. Use [cryptoFramework.createAsyKeyGeneratorBySpec](../../reference/apis-crypto-architecture-kit/js-apis-cryptoFramework.md#cryptoframeworkcreateasykeygeneratorbyspec10) with the **ECCCommonParamsSpec** object to create an asymmetric key generator (**AsyKeyGeneratorBySpec**) object.
102
1033. Use [AsyKeyGeneratorBySpec.generateKeyPair](../../reference/apis-crypto-architecture-kit/js-apis-cryptoFramework.md#generatekeypair-3) to generate a key pair (**KeyPair**).
104
1054. Use [PriKey.getAsyKeySpec](../../reference/apis-crypto-architecture-kit/js-apis-cryptoFramework.md#getasykeyspec10-1) to obtain the private key specifications, and use [PubKey.getAsyKeySpec](../../reference/apis-crypto-architecture-kit/js-apis-cryptoFramework.md#getasykeyspec10) to obtain the public key specifications of the ECC.
106
107- Example: Generate an ECC key pair based on key parameters (using promise-based APIs).
108  ```ts
109  import cryptoFramework from '@ohos.security.cryptoFramework';
110  import { BusinessError } from '@ohos.base';
111
112  // Print bigint information.
113  function showBigIntInfo(bnName: string, bnValue: bigint | string | number) {
114    if (typeof bnValue === 'string') {
115      console.error('type is string');
116      return;
117    }
118    if (typeof bnValue === 'number') {
119      console.error('type is number');
120      return;
121    }
122    console.info(bnName + ':');
123    console.info('. Decimal: ' + bnValue.toString());
124    console.info('. Hexadecimal: ' + bnValue.toString(16));
125    console.info('. Length (bits): ' + bnValue.toString(2).length);
126  }
127  // Construct the EccCommonSpec struct, which defines the common parameters of the ECC public and private keys.
128  function genEccCommonSpec(): cryptoFramework.ECCCommonParamsSpec {
129    let fieldFp: cryptoFramework.ECFieldFp = {
130      fieldType: 'Fp',
131      p: BigInt('0xffffffffffffffffffffffffffffffff000000000000000000000001')
132    }
133    let G: cryptoFramework.Point = {
134      x: BigInt('0xb70e0cbd6bb4bf7f321390b94a03c1d356c21122343280d6115c1d21'),
135      y: BigInt('0xbd376388b5f723fb4c22dfe6cd4375a05a07476444d5819985007e34')
136    }
137    let eccCommonSpec: cryptoFramework.ECCCommonParamsSpec = {
138      algName: 'ECC',
139      specType: cryptoFramework.AsyKeySpecType.COMMON_PARAMS_SPEC,
140      field: fieldFp,
141      a: BigInt('0xfffffffffffffffffffffffffffffffefffffffffffffffffffffffe'),
142      b: BigInt('0xb4050a850c04b3abf54132565044b0b7d7bfd8ba270b39432355ffb4'),
143      g: G,
144      n: BigInt('0xffffffffffffffffffffffffffff16a2e0b8f03e13dd29455c5c2a3d'),
145      h: 1
146    }
147    return eccCommonSpec;
148  }
149  // Print the ECC key specifications.
150  function showEccSpecDetailInfo(key: cryptoFramework.PubKey | cryptoFramework.PriKey, keyType: string) {
151    console.info('show detail of ' + keyType + ':');
152    try {
153      let p = key.getAsyKeySpec(cryptoFramework.AsyKeySpecItem.ECC_FP_P_BN);
154      showBigIntInfo('--- p', p); // length is 224, hex : ffffffffffffffffffffffffffffffff000000000000000000000001
155      let a = key.getAsyKeySpec(cryptoFramework.AsyKeySpecItem.ECC_A_BN);
156      showBigIntInfo('--- a', a); // length is 224, hex : fffffffffffffffffffffffffffffffefffffffffffffffffffffffe
157      let b = key.getAsyKeySpec(cryptoFramework.AsyKeySpecItem.ECC_B_BN);
158      showBigIntInfo('--- b', b); // length is 224, hex : b4050a850c04b3abf54132565044b0b7d7bfd8ba270b39432355ffb4
159      let gX = key.getAsyKeySpec(cryptoFramework.AsyKeySpecItem.ECC_G_X_BN);
160      showBigIntInfo('--- gX', gX); // length is 224, hex : b70e0cbd6bb4bf7f321390b94a03c1d356c21122343280d6115c1d21
161      let gY = key.getAsyKeySpec(cryptoFramework.AsyKeySpecItem.ECC_G_Y_BN);
162      showBigIntInfo('--- gY', gY); // length is 224, hex : bd376388b5f723fb4c22dfe6cd4375a05a07476444d5819985007e34
163      let n = key.getAsyKeySpec(cryptoFramework.AsyKeySpecItem.ECC_N_BN);
164      showBigIntInfo('--- n', n); // length is 224, hex : ffffffffffffffffffffffffffff16a2e0b8f03e13dd29455c5c2a3d
165      let h = key.getAsyKeySpec(cryptoFramework.AsyKeySpecItem.ECC_H_NUM);
166      console.warn('--- h: ' + h); // key h: 1
167      let fieldType = key.getAsyKeySpec(cryptoFramework.AsyKeySpecItem.ECC_FIELD_TYPE_STR);
168      console.warn('--- field type: ' + fieldType); // key field type: Fp
169      let fieldSize = key.getAsyKeySpec(cryptoFramework.AsyKeySpecItem.ECC_FIELD_SIZE_NUM);
170      console.warn('--- field size: ' + fieldSize); // key field size: 224
171      let curveName = key.getAsyKeySpec(cryptoFramework.AsyKeySpecItem.ECC_CURVE_NAME_STR);
172      console.warn('--- curve name: ' + curveName); // key curve name: NID_secp224r1
173      if (keyType == 'priKey') {
174        let sk = key.getAsyKeySpec(cryptoFramework.AsyKeySpecItem.ECC_SK_BN);
175        showBigIntInfo('--- sk', sk);
176      } else if (keyType == 'pubKey') {
177        let pkX = key.getAsyKeySpec(cryptoFramework.AsyKeySpecItem.ECC_PK_X_BN);
178        showBigIntInfo('--- pkX', pkX);
179        let pkY = key.getAsyKeySpec(cryptoFramework.AsyKeySpecItem.ECC_PK_Y_BN);
180        showBigIntInfo('--- pkY', pkY);
181      }
182    } catch (error) {
183      console.error('getAsyKeySpec error');
184      let e: BusinessError = error as BusinessError;
185      console.error(`getAsyKeySpec failed, ${e.code}, ${e.message}`);
186    }
187  }
188  // Generate an ECC key pair based on the EccCommonSpec instance and obtain the key specifications.
189  function testEccUseCommKeySpecGet() {
190    try {
191      let commKeySpec = genEccCommonSpec(); // Construct the EccCommonSpec object.
192      let generatorBySpec = cryptoFramework.createAsyKeyGeneratorBySpec(commKeySpec); // Create an AsyKeyGenerator instance based on the EccCommonSpec object.
193      let keyPairPromise = generatorBySpec.generateKeyPair(); // Generate an ECC key pair.
194      keyPairPromise.then(keyPair => {// Use AsyKeyGenerator to create an ECC key pair.
195        showEccSpecDetailInfo(keyPair.priKey, "priKey"); // Obtain the ECC private key specifications.
196        showEccSpecDetailInfo(keyPair.pubKey, "pubKey"); // Obtain the ECC public key specifications.
197      }).catch((error: BusinessError) => {
198        // Capture exceptions such as logic errors asynchronously.
199        console.error('generateComm error');
200        console.error('error code: ' + error.code + ', message is: ' + error.message);
201      })
202    } catch (error) {
203      // Capture parameter errors synchronously.
204      console.error('testEccUseCommSpec error');
205      let e: BusinessError = error as BusinessError;
206      console.error(`ecc comm spec failed, ${e.code}, ${e.message}`);
207    }
208  }
209}
210```
211
212
213## Generating an SM2 Key Pair Based on the Elliptic Curve Name
214
215For details about the algorithm specifications, see [SM2](crypto-asym-key-generation-conversion-spec.md#sm2).
216
2171. Create an [ECCCommonParamsSpec](../../reference/apis-crypto-architecture-kit/js-apis-cryptoFramework.md#ecccommonparamsspec10) object to specify common parameters of the private and public keys. Use [genECCCommonParamsSpec](../../reference/apis-crypto-architecture-kit/js-apis-cryptoFramework.md#genecccommonparamsspec11) with an NID string to generate the common parameters for the SM2 key pair.
218
219    When key parameters are specified for generating a key, the bigint value must be a positive number in big-endian format.
220
2212. Create an [ECCKeyPairSpec](../../reference/apis-crypto-architecture-kit/js-apis-cryptoFramework.md#ecckeypairspec10) object with **algName** set to **SM2** to specify the SM2 key pair parameters.
222
2233. Use [cryptoFramework.createAsyKeyGeneratorBySpec](../../reference/apis-crypto-architecture-kit/js-apis-cryptoFramework.md#cryptoframeworkcreateasykeygeneratorbyspec10) with the **ECCKeyPairSpec** object to create an asymmetric key generator object.
224
2254. Use [AsyKeyGeneratorBySpec.generateKeyPair](../../reference/apis-crypto-architecture-kit/js-apis-cryptoFramework.md#generatekeypair-3) to generate an SM2 key pair (**KeyPair**).
226
2275. Use [PriKey.getAsyKeySpec](../../reference/apis-crypto-architecture-kit/js-apis-cryptoFramework.md#getasykeyspec10-1) to obtain elliptic curve parameters of SM2.
228
229- Example: Generate an SM2 key based on the elliptic curve name (using promise-based APIs)
230  ```ts
231  import cryptoFramework from '@ohos.security.cryptoFramework';
232
233  function genSM2KeyPairSpec() {
234    let sm2CommonParamsSpec = cryptoFramework.ECCKeyUtil.genECCCommonParamsSpec('NID_sm2');
235    let sm2KeyPairSpec: cryptoFramework.ECCKeyPairSpec = {
236      algName: "SM2",
237      specType: cryptoFramework.AsyKeySpecType.KEY_PAIR_SPEC,
238      params: sm2CommonParamsSpec,
239      sk: BigInt('0x6330B599ECD23ABDC74B9A5B7B5E00E553005F72743101C5FAB83AEB579B7074'),
240      pk: {
241        x: BigInt('0x67F3B850BDC0BA5D3A29D8A0883C4B17612AB84F87F18E28F77D824A115C02C4'),
242        y: BigInt('0xD48966CE754BBBEDD6501A1385E1B205C186E926ADED44287145E8897D4B2071')
243      },
244    };
245    return sm2KeyPairSpec;
246  }
247
248  async function sm2Test() {
249    let sm2KeyPairSpec = genSM2KeyPairSpec();
250    let generatorBySpec = cryptoFramework.createAsyKeyGeneratorBySpec(sm2KeyPairSpec);
251    let keyPair = await generatorBySpec.generateKeyPair();
252    let sm2CurveName = keyPair.priKey.getAsyKeySpec(cryptoFramework.AsyKeySpecItem.ECC_CURVE_NAME_STR);
253    console.info('ECC_CURVE_NAME_STR: ' + sm2CurveName); // NID_sm2
254  }
255  ```
256