Computing the shared secret with Diffie-Hellman

In this example, Diffie-Hellman parameters are loaded from a PEM file and the peer's public key is loaded from an XML file. A private key is generated, and the shared secret is computed for secure communication.

Function generateKey is called with a 0, parameters are already filled.

IMPORT xml

FUNCTION BuildSharedSecret(DHdoc)
  DEFINE myKey, othersPubKey, sharedSecret xml.CryptoKey
  DEFINE DHdoc xml.DomDocument
  LET myKey =
    xml.CryptoKey.Create("http://www.w3.org/2001/04/xmlenc#DHKeyValue")
  LET othersPubKey =
    xml.CryptoKey.Create("http://www.w3.org/2001/04/xmlenc#DHKeyValue " )
  TRY
    CALL othersPubKey.loadPublic(DHdoc)

    # populate myKey with the parameters previously generated by the
    # other peer.
    CALL myKey.loadPEM("DHParam.pem")

    # Randomly generate a private key and compute the public key. 
    # Key length is the parameters length.
    CALL myKey.generateKey(0)
    LET sharedSecret = myKey.computeKey(othersPubKey,
      "http://www.w3.org/2000/09/xmldsig#hmac-sha1")

  CATCH
    DISPLAY "ERROR : should not raise exception"
    EXIT PROGRAM (-1)
  END TRY
END FUNCTION