Skip to content

Commit 614d646

Browse files
liuxingbaoyudanielleadams
authored andcommitted
src: fix crypto.privateEncrypt fails first time
`crypto.privateEncrypt` fails for the first time after `crypto.generateKeyPairSync` with certain parameters because the error stack is not cleaned up when `crypto.generateKeyPairSync` exits. Fixes: #40814 PR-URL: #42793 Reviewed-By: Ben Noordhuis <info@bnoordhuis.nl> Reviewed-By: James M Snell <jasnell@gmail.com> Reviewed-By: Filip Skokan <panva.ip@gmail.com>
1 parent 248de57 commit 614d646

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed

src/crypto/crypto_keys.cc

+1
Original file line numberDiff line numberDiff line change
@@ -319,6 +319,7 @@ MaybeLocal<Value> WritePrivateKey(
319319
}
320320
}
321321

322+
MarkPopErrorOnReturn mark_pop_error_on_return;
322323
bool err;
323324

324325
PKEncodingType encoding_type = config.type_.ToChecked();
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
'use strict';
2+
const common = require('../common');
3+
4+
// Test for https://github.com/nodejs/node/issues/40814
5+
6+
if (!common.hasCrypto)
7+
common.skip('missing crypto');
8+
9+
if (!common.hasOpenSSL3)
10+
common.skip('only openssl3'); // https://github.com/nodejs/node/pull/42793#issuecomment-1107491901
11+
12+
const assert = require('assert');
13+
const crypto = require('crypto');
14+
15+
const { privateKey, publicKey } = crypto.generateKeyPairSync('rsa', {
16+
modulusLength: 2048,
17+
publicKeyEncoding: {
18+
type: 'spki',
19+
format: 'pem'
20+
},
21+
privateKeyEncoding: {
22+
type: 'pkcs8',
23+
format: 'pem',
24+
cipher: 'aes-128-ecb',
25+
passphrase: 'abcdef'
26+
}
27+
});
28+
assert.notStrictEqual(privateKey.toString(), '');
29+
30+
const msg = 'The quick brown fox jumps over the lazy dog';
31+
32+
const encryptedString = crypto.privateEncrypt({
33+
key: privateKey,
34+
passphrase: 'abcdef'
35+
}, Buffer.from(msg)).toString('base64');
36+
const decryptedString = crypto.publicDecrypt(publicKey, Buffer.from(encryptedString, 'base64')).toString();
37+
console.log(`Encrypted: ${encryptedString}`);
38+
console.log(`Decrypted: ${decryptedString}`);
39+
40+
assert.notStrictEqual(encryptedString, '');
41+
assert.strictEqual(decryptedString, msg);

0 commit comments

Comments
 (0)