Node.js ecdh.computeSecret() Method
The ecdh.computeSecret() method is an inbuilt application programming interface of class ECDH within the crypto module which is used to create the shared secret using the public key of the other party. The encoding of both the input public key and the output secret key can be specified using the respective parameters.
The ERR_CRYPTO_ECDH_INVALID_PUBLIC_KEY error is thrown when the public key lies outside of the elliptic curve.
ecdh.computeSecret( otherPublicKey, inputEncoding, outputEncoding )
Parameters: This method accepts three parameters as mentioned above and described below:
- otherPublicKey: It is the other party’s public key based on which the shared secret is generated.
- inputEncoding: This is a string value that specifies the encoding of the other party’s public key. When this parameter is not specified, the key is expected as a Buffer TypedArray, or DataView.
- outputEncoding: This is a string value that specifies the encoding of the shared secret that will be generated.
Return Value: It returns the Elliptic Curve DiffieHellman shared secret key in the specified encoding. When the encoding is not provided, it is returned as a Buffer, otherwise a string is returned.
The below examples demonstrate the method:
Example 1: In this example, the shared secrets of both users are created using the keys of both parties and then they are compared to see if they are equal.
Secret of A is: Ac7p1CjFXyTrdcVxx0HIs0Jqjr3fGb7sUTxfgdUQ+xgXmpJgWKS9SECkFf3ehly+xyvE2MtWFcAxF2gq9F7k7tT5
Secret of B is: Ac7p1CjFXyTrdcVxx0HIs0Jqjr3fGb7sUTxfgdUQ+xgXmpJgWKS9SECkFf3ehly+xyvE2MtWFcAxF2gq9F7k7tT5
The secrets match!
Example 2: In this example, the inputEncoding parameter is passed as null as the generateKeys() method does not encode the keys when generating them.
Secret of Geek One is: ACc+SKe9XQMw5quzSEKs0Os+OhGKPRqHIwkW13+lxhs2HNwUEvbZdCEOE/PCzdNKk3v5zqdWSHO0kfRy1qBM8Kc6
Secret of Geek Two is: ACc+SKe9XQMw5quzSEKs0Os+OhGKPRqHIwkW13+lxhs2HNwUEvbZdCEOE/PCzdNKk3v5zqdWSHO0kfRy1qBM8Kc6