From 0be6f95661fa28b9ca0345959e1e8765c641e009 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tobias=20Nie=C3=9Fen?= Date: Sat, 26 Jan 2019 13:28:55 +0100 Subject: [PATCH] crypto: allow deriving public from private keys This change allows passing private key objects to crypto.createPublicKey, resulting in a key object that represents a valid public key for the given private key. The returned public key object can be used and exported safely without revealing information about the private key. Backport-PR-URL: https://github.com/nodejs/node/pull/26688 PR-URL: https://github.com/nodejs/node/pull/26278 Reviewed-By: James M Snell Reviewed-By: Ben Noordhuis Reviewed-By: Sam Roberts --- doc/api/crypto.md | 17 +++++--- lib/internal/crypto/keys.js | 50 +++++++++++++++--------- test/parallel/test-crypto-key-objects.js | 36 ++++++++++++++++- 3 files changed, 78 insertions(+), 25 deletions(-) diff --git a/doc/api/crypto.md b/doc/api/crypto.md index d933f8fe09e8b9..c627a0817d7325 100644 --- a/doc/api/crypto.md +++ b/doc/api/crypto.md @@ -1817,11 +1817,15 @@ must be an object with the properties described above. -* `key` {Object | string | Buffer} +* `key` {Object | string | Buffer | KeyObject} - `key`: {string | Buffer} - `format`: {string} Must be `'pem'` or `'der'`. **Default:** `'pem'`. - `type`: {string} Must be `'pkcs1'` or `'spki'`. This option is required @@ -1829,16 +1833,19 @@ changes: * Returns: {KeyObject} Creates and returns a new key object containing a public key. If `key` is a -string or `Buffer`, `format` is assumed to be `'pem'`; otherwise, `key` -must be an object with the properties described above. +string or `Buffer`, `format` is assumed to be `'pem'`; if `key` is a `KeyObject` +with type `'private'`, the public key is derived from the given private key; +otherwise, `key` must be an object with the properties described above. If the format is `'pem'`, the `'key'` may also be an X.509 certificate. Because public keys can be derived from private keys, a private key may be passed instead of a public key. In that case, this function behaves as if [`crypto.createPrivateKey()`][] had been called, except that the type of the -returned `KeyObject` will be `public` and that the private key cannot be -extracted from the returned `KeyObject`. +returned `KeyObject` will be `'public'` and that the private key cannot be +extracted from the returned `KeyObject`. Similarly, if a `KeyObject` with type +`'private'` is given, a new `KeyObject` with type `'public'` will be returned +and it will be impossible to extract the private key from the returned object. ### crypto.createSecretKey(key)