1'use strict';
2
3const common = require('../common');
4if (!common.hasCrypto)
5  common.skip('missing crypto');
6
7const assert = require('assert');
8const {
9  createPrivateKey,
10  generateKeyPair,
11} = require('crypto');
12const {
13  testSignVerify,
14} = require('../common/crypto');
15
16// Passing an empty passphrase string should not cause OpenSSL's default
17// passphrase prompt in the terminal.
18// See https://github.com/nodejs/node/issues/35898.
19for (const type of ['pkcs1', 'pkcs8']) {
20  generateKeyPair('rsa', {
21    modulusLength: 1024,
22    privateKeyEncoding: {
23      type,
24      format: 'pem',
25      cipher: 'aes-256-cbc',
26      passphrase: ''
27    }
28  }, common.mustSucceed((publicKey, privateKey) => {
29    assert.strictEqual(publicKey.type, 'public');
30
31    for (const passphrase of ['', Buffer.alloc(0)]) {
32      const privateKeyObject = createPrivateKey({
33        passphrase,
34        key: privateKey
35      });
36      assert.strictEqual(privateKeyObject.asymmetricKeyType, 'rsa');
37    }
38
39    // Encrypting with an empty passphrase is not the same as not encrypting
40    // the key, and not specifying a passphrase should fail when decoding it.
41    assert.throws(() => {
42      return testSignVerify(publicKey, privateKey);
43    }, common.hasOpenSSL3 ? {
44      name: 'Error',
45      code: 'ERR_OSSL_CRYPTO_INTERRUPTED_OR_CANCELLED',
46      message: 'error:07880109:common libcrypto routines::interrupted or cancelled'
47    } : {
48      name: 'TypeError',
49      code: 'ERR_MISSING_PASSPHRASE',
50      message: 'Passphrase required for encrypted key'
51    });
52  }));
53}
54