Skip to content

Commit

Permalink
src: fix crypto.privateEncrypt fails first time
Browse files Browse the repository at this point in the history
`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>
  • Loading branch information
liuxingbaoyu authored and danielleadams committed Jan 3, 2023
1 parent 248de57 commit 614d646
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/crypto/crypto_keys.cc
Expand Up @@ -319,6 +319,7 @@ MaybeLocal<Value> WritePrivateKey(
}
}

MarkPopErrorOnReturn mark_pop_error_on_return;
bool err;

PKEncodingType encoding_type = config.type_.ToChecked();
Expand Down
41 changes: 41 additions & 0 deletions test/parallel/test-crypto-publicDecrypt-fails-first-time.js
@@ -0,0 +1,41 @@
'use strict';
const common = require('../common');

// Test for https://github.com/nodejs/node/issues/40814

if (!common.hasCrypto)
common.skip('missing crypto');

if (!common.hasOpenSSL3)
common.skip('only openssl3'); // https://github.com/nodejs/node/pull/42793#issuecomment-1107491901

const assert = require('assert');
const crypto = require('crypto');

const { privateKey, publicKey } = crypto.generateKeyPairSync('rsa', {
modulusLength: 2048,
publicKeyEncoding: {
type: 'spki',
format: 'pem'
},
privateKeyEncoding: {
type: 'pkcs8',
format: 'pem',
cipher: 'aes-128-ecb',
passphrase: 'abcdef'
}
});
assert.notStrictEqual(privateKey.toString(), '');

const msg = 'The quick brown fox jumps over the lazy dog';

const encryptedString = crypto.privateEncrypt({
key: privateKey,
passphrase: 'abcdef'
}, Buffer.from(msg)).toString('base64');
const decryptedString = crypto.publicDecrypt(publicKey, Buffer.from(encryptedString, 'base64')).toString();
console.log(`Encrypted: ${encryptedString}`);
console.log(`Decrypted: ${decryptedString}`);

assert.notStrictEqual(encryptedString, '');
assert.strictEqual(decryptedString, msg);

0 comments on commit 614d646

Please sign in to comment.