Skip to content

Commit e175d0b

Browse files
tniessentargos
authored andcommitted
crypto: reject public keys properly
Fixes: #29904 PR-URL: #29913 Reviewed-By: Sam Roberts <[email protected]> Reviewed-By: Colin Ihrig <[email protected]> Reviewed-By: James M Snell <[email protected]> Reviewed-By: Ben Noordhuis <[email protected]>
1 parent f3115c4 commit e175d0b

File tree

2 files changed

+25
-1
lines changed

2 files changed

+25
-1
lines changed

lib/internal/crypto/keys.js

+4-1
Original file line numberDiff line numberDiff line change
@@ -270,7 +270,10 @@ function prepareAsymmetricKey(key, ctx) {
270270
...(ctx !== kCreatePrivate ? ['KeyObject'] : [])],
271271
key);
272272
}
273-
return { data, ...parseKeyEncoding(key, undefined) };
273+
274+
const isPublic =
275+
(ctx === kConsumePrivate || ctx === kCreatePrivate) ? false : undefined;
276+
return { data, ...parseKeyEncoding(key, undefined, isPublic) };
274277
} else {
275278
throw new ERR_INVALID_ARG_TYPE(
276279
'key',

test/parallel/test-crypto-key-objects.js

+21
Original file line numberDiff line numberDiff line change
@@ -200,6 +200,27 @@ const privateDsa = fixtures.readKey('dsa_private_encrypted_1025.pem',
200200
library: 'BIO routines',
201201
function: 'BIO_new_mem_buf',
202202
});
203+
204+
// This should not abort either: https://github.com/nodejs/node/issues/29904
205+
assert.throws(() => {
206+
createPrivateKey({ key: Buffer.alloc(0), format: 'der', type: 'spki' });
207+
}, {
208+
code: 'ERR_INVALID_OPT_VALUE',
209+
message: 'The value "spki" is invalid for option "type"'
210+
});
211+
212+
// Unlike SPKI, PKCS#1 is a valid encoding for private keys (and public keys),
213+
// so it should be accepted by createPrivateKey, but OpenSSL won't parse it.
214+
assert.throws(() => {
215+
const key = createPublicKey(publicPem).export({
216+
format: 'der',
217+
type: 'pkcs1'
218+
});
219+
createPrivateKey({ key, format: 'der', type: 'pkcs1' });
220+
}, {
221+
message: /asn1 encoding/,
222+
library: 'asn1 encoding routines'
223+
});
203224
}
204225

205226
[

0 commit comments

Comments
 (0)