Skip to content

Commit e175d0b

Browse files
tniessentargos
authored andcommitted
crypto: reject public keys properly
Fixes: #29904 PR-URL: #29913 Reviewed-By: Sam Roberts <vieuxtech@gmail.com> Reviewed-By: Colin Ihrig <cjihrig@gmail.com> Reviewed-By: James M Snell <jasnell@gmail.com> Reviewed-By: Ben Noordhuis <info@bnoordhuis.nl>
1 parent f3115c4 commit e175d0b

2 files changed

Lines changed: 25 additions & 1 deletion

File tree

‎lib/internal/crypto/keys.js‎

Lines changed: 4 additions & 1 deletion
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+
constisPublic=
275+
(ctx===kConsumePrivate||ctx===kCreatePrivate) ? false : undefined;
276+
return{ data, ...parseKeyEncoding(key,undefined,isPublic)};
274277
}else{
275278
thrownewERR_INVALID_ARG_TYPE(
276279
'key',

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

Lines changed: 21 additions & 0 deletions
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+
constkey=createPublicKey(publicPem).export({
216+
format: 'der',
217+
type: 'pkcs1'
218+
});
219+
createPrivateKey({ key,format: 'der',type: 'pkcs1'});
220+
},{
221+
message: /asn1encoding/,
222+
library: 'asn1 encoding routines'
223+
});
203224
}
204225

205226
[

0 commit comments

Comments
 (0)