googleapis / google-p12-pem

**THIS REPOSITORY AND PACKAGE WILL BE DEPRECATED IN JULY 2024** Convert Google .p12 keys to .pem keys.
MIT License
26 stars 22 forks source link

ERROR: Cannot read properties of undefined (reading 'n') #451

Closed itzrahulsoni closed 1 week ago

itzrahulsoni commented 5 months ago

Environment details

Steps to reproduce

  1. Create a new P12 key for a Google service account
  2. Use the sample code provided in this repository
const { getPem } = require('google-p12-pem');

/**
 * Given a p12 file, convert it to the PEM format.
 * @param {string} pathToCert The relative path to a p12 file.
 */
async function quickstart() {
  // TODO(developer): provide the path to your cert
  const pathToCert = '/MYPATH/GOOGLE_P12_PATH.p12';

  const pem = await getPem(pathToCert);
  console.log('The converted PEM:');
  console.log(pem);
}

quickstart();

Error:

MYPATH/test/node_modules/node-forge/lib/rsa.js:1434
      _bnToBytes(key.n)),
                     ^

TypeError: Cannot read properties of undefined (reading 'n')
    at pki.privateKeyToAsn1.pki.privateKeyToRSAPrivateKey (MYPATH/test/node_modules/node-forge/lib/rsa.js:1434:22)
    at pki.privateKeyToPem (MYPATH/test/node_modules/node-forge/lib/pki.js:82:26)
    at convertToPem (MYPATH/test/node_modules/google-p12-pem/build/src/index.js:42:31)
    at MYPATH/test/node_modules/google-p12-pem/build/src/index.js:27:16
    at async quickstart (MYPATH/test/index.js:11:15)

Inside node_modules/google-p12-pem/build/src/index.js:

function convertToPem(p12base64) {
    const p12Der = forge.util.decode64(p12base64);
    const p12Asn1 = forge.asn1.fromDer(p12Der);
    const p12 = forge.pkcs12.pkcs12FromAsn1(p12Asn1, 'notasecret');
    const bags = p12.getBags({ friendlyName: 'privatekey' });
    if (bags.friendlyName) {
        const privateKey = bags.friendlyName[0].key;
        const pem = forge.pki.privateKeyToPem(privateKey);
        return pem.replace(/\r\n/g, '\n');
    }
    else {
        throw new Error('Unable to get friendly name.');
    }
}

If I change the following:

        const privateKey = bags.friendlyName[0].key;

to:

        const privateKey = bags.friendlyName[1].key;

Things work as expected. How do I deal with this? Is there a reason for using first key and not the second? Why is it hard coded?