Skip to content

Commit 1d2f4c4

Browse files
panvaBethGriggs
authored andcommitted
crypto: fix crash of encrypted private key export without cipher
PR-URL: #27041 Reviewed-By: Ben Noordhuis <info@bnoordhuis.nl> Reviewed-By: Ruben Bridgewater <ruben@bridgewater.de> Signed-off-by: Beth Griggs <Bethany.Griggs@uk.ibm.com>
1 parent 755609c commit 1d2f4c4

File tree

2 files changed

+25
-7
lines changed

2 files changed

+25
-7
lines changed

lib/internal/crypto/keys.js

+11-7
Original file line numberDiff line numberDiff line change
@@ -186,14 +186,18 @@ function parseKeyEncoding(enc, keyType, isPublic, objName) {
186186
if (isPublic !== true) {
187187
({ cipher, passphrase } = enc);
188188

189-
if (!isInput && cipher != null) {
190-
if (typeof cipher !== 'string')
189+
if (!isInput) {
190+
if (cipher != null) {
191+
if (typeof cipher !== 'string')
192+
throw new ERR_INVALID_OPT_VALUE(option('cipher', objName), cipher);
193+
if (format === kKeyFormatDER &&
194+
(type === kKeyEncodingPKCS1 ||
195+
type === kKeyEncodingSEC1)) {
196+
throw new ERR_CRYPTO_INCOMPATIBLE_KEY_OPTIONS(
197+
encodingNames[type], 'does not support encryption');
198+
}
199+
} else if (passphrase !== undefined) {
191200
throw new ERR_INVALID_OPT_VALUE(option('cipher', objName), cipher);
192-
if (format === kKeyFormatDER &&
193-
(type === kKeyEncodingPKCS1 ||
194-
type === kKeyEncodingSEC1)) {
195-
throw new ERR_CRYPTO_INCOMPATIBLE_KEY_OPTIONS(
196-
encodingNames[type], 'does not support encryption');
197201
}
198202
}
199203

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

+14
Original file line numberDiff line numberDiff line change
@@ -167,3 +167,17 @@ const privatePem = fixtures.readSync('test_rsa_privkey.pem', 'ascii');
167167
createPrivateKey({ key: '' });
168168
}, /null/);
169169
}
170+
171+
{
172+
// Exporting an encrypted private key requires a cipher
173+
const privateKey = createPrivateKey(privatePem);
174+
common.expectsError(() => {
175+
privateKey.export({
176+
format: 'pem', type: 'pkcs8', passphrase: 'super-secret'
177+
});
178+
}, {
179+
type: TypeError,
180+
code: 'ERR_INVALID_OPT_VALUE',
181+
message: 'The value "undefined" is invalid for option "cipher"'
182+
});
183+
}

0 commit comments

Comments
 (0)