Stability: 0 - Deprecated

    • publicKey {string | Buffer | TypedArray | DataView}
    • encoding {string} The [encoding][] of the publicKey string.

    Sets the EC Diffie-Hellman public key. If encoding is provided publicKey is expected to be a string; otherwise a [Buffer][], TypedArray, or DataView is expected.

    There is not normally a reason to call this method because ECDH only requires a private key and the other party’s public key to compute the shared secret. Typically either [ecdh.generateKeys()][] or [ecdh.setPrivateKey()][] will be called. The [ecdh.setPrivateKey()][] method attempts to generate the public point/key associated with the private key being set.

    Example (obtaining a shared secret):

    1. const crypto = require('crypto');
    2. const alice = crypto.createECDH('secp256k1');
    3. const bob = crypto.createECDH('secp256k1');
    4. // This is a shortcut way of specifying one of Alice's previous private
    5. // keys. It would be unwise to use such a predictable private key in a real
    6. // application.
    7. alice.setPrivateKey(
    8. crypto.createHash('sha256').update('alice', 'utf8').digest()
    9. );
    10. // Bob uses a newly generated cryptographically strong
    11. // pseudorandom key pair
    12. bob.generateKeys();
    13. const aliceSecret = alice.computeSecret(bob.getPublicKey(), null, 'hex');
    14. const bobSecret = bob.computeSecret(alice.getPublicKey(), null, 'hex');
    15. // aliceSecret and bobSecret should be the same shared secret value
    16. console.log(aliceSecret === bobSecret);