DEV Community

HarmonyOS
HarmonyOS

Posted on

Generate DH Key Pair

Read the original article:Generate DH Key Pair

Requirement Description

How to generate a Diffie–Hellman (DH) key pair, including the detailed generation process and code examples.

Background Knowledge

DH (Diffie–Hellman) Key Exchange Algorithm

  • A cryptographic key agreement protocol that allows two parties to establish a shared secret key over an insecure channel.
  • It provides forward secrecy, ensuring that even if communication is intercepted, private keys remain secure.

HarmonyOS supports two approaches to generate DH key pairs:

  1. Using string parameters (simplified algorithm specification)
  2. Using explicit key parameters (custom p, g, and private/public key values)

Relevant APIs:

API Description
DHCommonParamsSpec Specifies the DH algorithm’s common parameters (p, g, l).
DHPriKeySpec Specifies the DH private key parameters.
DHPubKeySpec Specifies the DH public key parameters.
DHKeyPairSpec Defines a full DH key parameter set.
createAsyKeyGeneratorBySpec() Creates an asymmetric key generator using custom parameters.
createAsyKeyGenerator() Creates an asymmetric key generator using algorithm name string.

Implementation Steps

  1. Generate DH Key Using String Parameters
  2. Generate DH Key Using Custom Parameters

Code Snippets

Scenario 1: Generate DH Key Using String Parameters

This is the simplest approach—no need to manually specify p, g, or l.

import { cryptoFramework } from '@kit.CryptoArchitectureKit'

// Generate DH key pair using string parameter
export function getDHKeyFromStringParams() {
  try {
    // 1. Create asymmetric key generator using predefined DH algorithm
    let spec = cryptoFramework.createAsyKeyGenerator('DH_modp2048')

    // 2. Generate key pair
    let keyPair = spec.generateKeyPairSync()
    let pubKey = keyPair.pubKey.getEncoded().data
    let priKey = keyPair.priKey.getEncoded().data

    console.info(`getDHKeyFromStringParams success, DH public key = ${pubKey.toString()}`)
    console.info(`getDHKeyFromStringParams success, DH private key = ${priKey.toString()}`)
  } catch (error) {
    console.error(`getDHKeyFromStringParams failed, error = ${JSON.stringify(error)}`)
  }
}
Enter fullscreen mode Exit fullscreen mode

Use Case: Quick generation of standard DH key pairs for testing or secure communication.

Scenario 2: Generate DH Key Using Custom Parameters

This approach allows specifying custom prime (p), base (g), and key length (l).

import { cryptoFramework } from '@kit.CryptoArchitectureKit'

// Generate DH key pair using explicit key parameters
export function getDHKeyFromParams() {
  try {
    // 1. Define DH common parameters
    let dHCommonParamsSpec: cryptoFramework.DHCommonParamsSpec = {
      p: BigInt('0xb70e0cbd6bb4bf7f321390b94a03c1d356c21122343280d6115c1d21'),
      g: BigInt('0xbd376388b5f723fb4c22dfe6cd4375a05a07476444d5819985007e34'),
      l: 192,
      algName: 'DH',
      specType: cryptoFramework.AsyKeySpecType.COMMON_PARAMS_SPEC
    };

    // 2. Define DH key pair specification
    let dHKeyPairSpec: cryptoFramework.DHKeyPairSpec = {
      sk: BigInt('0xfffffffffffffffffffffffffffffffefffffffffffffffffffffffe'),
      pk: BigInt('0xb4050a850c04b3abf54132565044b0b7d7bfd8ba270b39432355ffb4'),
      params: dHCommonParamsSpec,
      algName: 'DH',
      specType: cryptoFramework.AsyKeySpecType.KEY_PAIR_SPEC
    };

    // 3. Create key generator from specification
    let spec = cryptoFramework.createAsyKeyGeneratorBySpec(dHKeyPairSpec)

    // 4. Generate key pair
    let keyPair = spec.generateKeyPairSync()
    let pubKey = keyPair.pubKey.getEncoded().data
    let priKey = keyPair.priKey.getEncoded().data

    console.info(`getDHKeyFromParams success, DH public key = ${pubKey.toString()}`)
    console.info(`getDHKeyFromParams success, DH private key = ${priKey.toString()}`)
  } catch (error) {
    console.error(`getDHKeyFromParams failed, error = ${JSON.stringify(error)}`)
  }
}
Enter fullscreen mode Exit fullscreen mode

Use Case: When you need to generate DH keys with specific security parameters or to match an existing cryptographic setup.

Successfully generates both public and private keys using both methods.

Limitations or Considerations

  • Private key length l is optional, default is 0.

    • Recommended range:
    l > 2 × (96 + (bitLength(p) - 1) / 1024 × 16)
    
    • Prime p must satisfy:
    512 bits  bitLength(p)  10000 bits
    
    • Key generation requires CryptoArchitectureKit.

Written by Arif Emre Ankara

Top comments (0)