From f2e02883e7ef6ff58331e980f91bc31d8076a5c8 Mon Sep 17 00:00:00 2001 From: Wei-Wei Wu Date: Thu, 1 Mar 2018 17:13:12 -0800 Subject: [PATCH] crypto: add ECDH.convertKey to convert public keys ECDH.convertKey is used to convert public keys between different formats. PR-URL: https://github.com/nodejs/node/pull/19080 Fixes: https://github.com/nodejs/node/issues/18977 Reviewed-By: Ben Noordhuis Reviewed-By: James M Snell --- doc/api/crypto.md | 48 +++++++++ lib/internal/crypto/diffiehellman.js | 82 ++++++++------ src/node_crypto.cc | 83 ++++++++++++-- src/node_crypto.h | 6 +- test/parallel/test-crypto-ecdh-convert-key.js | 101 ++++++++++++++++++ 5 files changed, 275 insertions(+), 45 deletions(-) create mode 100644 test/parallel/test-crypto-ecdh-convert-key.js diff --git a/doc/api/crypto.md b/doc/api/crypto.md index 7073cf2249d658..4c2354f52eb44d 100644 --- a/doc/api/crypto.md +++ b/doc/api/crypto.md @@ -656,6 +656,54 @@ assert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex')); // OK ``` +### ECDH.convertKey(key, curve[, inputEncoding[, outputEncoding[, format]]]) + + +- `key` {string | Buffer | TypedArray | DataView} +- `curve` {string} +- `inputEncoding` {string} +- `outputEncoding` {string} +- `format` {string} Defaults to `uncompressed`. + +Converts the EC Diffie-Hellman public key specified by `key` and `curve` to the +format specified by `format`. The `format` argument specifies point encoding +and can be `'compressed'`, `'uncompressed'` or `'hybrid'`. The supplied key is +interpreted using the specified `inputEncoding`, and the returned key is encoded +using the specified `outputEncoding`. Encodings can be `'latin1'`, `'hex'`, +or `'base64'`. + +Use [`crypto.getCurves()`][] to obtain a list of available curve names. +On recent OpenSSL releases, `openssl ecparam -list_curves` will also display +the name and description of each available elliptic curve. + +If `format` is not specified the point will be returned in `'uncompressed'` +format. + +If the `inputEncoding` is not provided, `key` is expected to be a [`Buffer`][], +`TypedArray`, or `DataView`. + +Example (uncompressing a key): + +```js +const { ECDH } = require('crypto'); + +const ecdh = ECDH('secp256k1'); +ecdh.generateKeys(); + +const compressedKey = ecdh.getPublicKey('hex', 'compressed'); + +const uncompressedKey = ECDH.convertKey(compressedKey, + 'secp256k1', + 'hex', + 'hex', + 'uncompressed'); + +// the converted key and the uncompressed public key should be the same +console.log(uncompressedKey === ecdh.getPublicKey('hex')); +``` + ### ecdh.computeSecret(otherPublicKey[, inputEncoding][, outputEncoding])