• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Key Agreement Using DH
2
3
4For details about the algorithm specifications, see [DH](crypto-key-agreement-overview.md#dh).
5
6
7## How to Develop
8
91. Use [cryptoFramework.createAsyKeyGenerator](../../reference/apis-crypto-architecture-kit/js-apis-cryptoFramework.md#cryptoframeworkcreateasykeygenerator) and [AsyKeyGenerator.generateKeyPair](../../reference/apis-crypto-architecture-kit/js-apis-cryptoFramework.md#generatekeypair-1) to generate a DH asymmetric key pair (**KeyPair**) with the named DH group **modp1536**.
10   In addition to the example in this topic, [DH](crypto-asym-key-generation-conversion-spec.md#dh) and [Randomly Generating an Asymmetric Key Pair](crypto-generate-asym-key-pair-randomly.md) may help you better understand how to generate a DH asymmetric key pair. Note that the input parameters in the reference documents may be different from those in the example below.
11
122. Use [cryptoFramework.createKeyAgreement](../../reference/apis-crypto-architecture-kit/js-apis-cryptoFramework.md#cryptoframeworkcreatekeyagreement) with the string parameter **'DH_modp1536'** to create a key agreement (**KeyAgreement**) instance.
13
143. Use [KeyAgreement.generateSecret](../../reference/apis-crypto-architecture-kit/js-apis-cryptoFramework.md#generatesecret-1) to perform key agreement with the specified private key (**KeyPair.pubKey**) and public key (**KeyPair.priKey**), and return the shared secret.
15
16Example: Perform key agreement using **await**.
17```ts
18import cryptoFramework from '@ohos.security.cryptoFramework';
19
20async function dhAwait() {
21  let keyGen = cryptoFramework.createAsyKeyGenerator('DH_modp1536');
22  // Randomly generate public-private key pair A.
23  let keyPairA = await keyGen.generateKeyPair();
24  // Randomly generate public-private key pair B with the same specifications.
25  let keyPairB = await keyGen.generateKeyPair();
26  let keyAgreement = cryptoFramework.createKeyAgreement('DH_modp1536');
27  // Use the public key of A and the private key of B to perform key agreement.
28  let secret1 = await keyAgreement.generateSecret(keyPairB.priKey, keyPairA.pubKey);
29  // Use the private key of A and the public key of B to perform key agreement.
30  let secret2 = await keyAgreement.generateSecret(keyPairA.priKey, keyPairB.pubKey);
31  // The two key agreement results should be the same.
32  if (secret1.data.toString() == secret2.data.toString()) {
33    console.info('DH success');
34    console.info('DH output is ' + secret1.data);
35  } else {
36    console.error('DH result is not equal');
37  }
38}
39```
40