Skip to content

Commit b2bb6c2

Browse files
panvaBridgeAR
authored andcommitted
crypto: fix crash of encrypted private key export without cipher
PR-URL: #27041 Reviewed-By: Ben Noordhuis <[email protected]> Reviewed-By: Ruben Bridgewater <[email protected]>
1 parent 6fb32ac commit b2bb6c2

File tree

2 files changed

+25
-7
lines changed

2 files changed

+25
-7
lines changed

lib/internal/crypto/keys.js

Lines changed: 11 additions & 7 deletions
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

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -244,3 +244,17 @@ const privateDsa = fixtures.readKey('dsa_private_encrypted_1025.pem',
244244
assert.strictEqual(privateKey.asymmetricKeyType, 'dsa');
245245
assert.strictEqual(privateKey.symmetricKeySize, undefined);
246246
}
247+
248+
{
249+
// Exporting an encrypted private key requires a cipher
250+
const privateKey = createPrivateKey(privatePem);
251+
common.expectsError(() => {
252+
privateKey.export({
253+
format: 'pem', type: 'pkcs8', passphrase: 'super-secret'
254+
});
255+
}, {
256+
type: TypeError,
257+
code: 'ERR_INVALID_OPT_VALUE',
258+
message: 'The value "undefined" is invalid for option "cipher"'
259+
});
260+
}

0 commit comments

Comments
 (0)