Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

crypto: reject public keys properly #29913

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion lib/internal/crypto/keys.js
Original file line number Diff line number Diff line change
Expand Up @@ -270,7 +270,10 @@ function prepareAsymmetricKey(key, ctx) {
...(ctx !== kCreatePrivate ? ['KeyObject'] : [])],
key);
}
return { data, ...parseKeyEncoding(key, undefined) };

const isPublic =
(ctx === kConsumePrivate || ctx === kCreatePrivate) ? false : undefined;
return { data, ...parseKeyEncoding(key, undefined, isPublic) };
} else {
throw new ERR_INVALID_ARG_TYPE(
'key',
Expand Down
21 changes: 21 additions & 0 deletions test/parallel/test-crypto-key-objects.js
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,27 @@ const privateDsa = fixtures.readKey('dsa_private_encrypted_1025.pem',
library: 'BIO routines',
function: 'BIO_new_mem_buf',
});

// This should not abort either: https://github.com/nodejs/node/issues/29904
assert.throws(() => {
createPrivateKey({ key: Buffer.alloc(0), format: 'der', type: 'spki' });
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There are other formats for public keys, perhaps its worth testing them all?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think the only other supported type is pkcs1 which behaves differently, but I added a test case for that as well.

}, {
code: 'ERR_INVALID_OPT_VALUE',
message: 'The value "spki" is invalid for option "type"'
});

// Unlike SPKI, PKCS#1 is a valid encoding for private keys (and public keys),
// so it should be accepted by createPrivateKey, but OpenSSL won't parse it.
assert.throws(() => {
const key = createPublicKey(publicPem).export({
format: 'der',
type: 'pkcs1'
});
createPrivateKey({ key, format: 'der', type: 'pkcs1' });
}, {
message: /asn1 encoding/,
library: 'asn1 encoding routines'
});
}

[
Expand Down