Search code examples
javaencryptionrsabouncycastle

Read private key from PFX file, decrypt the ciphertext with that private key


I trying to get the private key from password protected PFX file, and do the decryption with the help of the extracted private key.Tried the following code, but getting the NullPointerException.

    Security.addProvider(new BouncyCastleProvider());
    PEMParser pemParser = new PEMParser(new InputStreamReader(new FileInputStream("..//pfx//pfx//BC_6.pfx")));
    PEMEncryptedKeyPair encryptedKeyPair = (PEMEncryptedKeyPair) pemParser.readObject();
    PEMDecryptorProvider decryptorProvider = new JcePEMDecryptorProviderBuilder().build("test123".toCharArray());
    PEMKeyPair pemKeyPair = encryptedKeyPair.decryptKeyPair(decryptorProvider);

    JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC");
    System.out.println(" Private Key --->  "+converter.getPrivateKey(pemKeyPair.getPrivateKeyInfo()));

Output is,

Exception in thread "main" java.lang.NullPointerException
at com.test.obfuscate.EncryptionUtil.main(EncryptionUtil.java:40)

Please suggest on this, stuck with this from past one week. Tried different posts from StackOverflow.


Solution

  • PEMParser pemParser = new PEMParser(new InputStreamReader(new FileInputStream("..//pfx//pfx//BC_6.pfx")));

    Are you trying to read the PFX file as a PEM file?? The PFX file is effectively PKCS12 keystore.

    So (typing from my head, please don't mind small typos / syntax errors)

    InputStream in = ...
    KeyStore ks = KeyStore.getInstance("PKCS12");
    ks.load(in);