How to resolve RSA private key failed to load from pkcs12

Vignesh S
2 min readMay 17, 2021

I faced the issue when updating the expired PKCS12 with the newly provided PKCS12 file in our server.

What it contains & why it is used?
PKCS12 file holds the certificates as well as the encrypted private key of the server. This file is then distributed to the clients to make a secure connection to the server’s REST endpoints.

The below is the exception which we received when updated the new file in our server. This is occurring when we are extracting the private key it appends with the redundant 0s leads to an Invalid Key Exception.

Invalid RSA Private key

How to resolve this?
Execute the below steps with the help of OpenSSL to remove the redundant 0s while extracting the private key. We can apply the commands to normalize an affected pkcs12 file

Use the below code to test the changes locally with the newly generated pkcs12 file.

public class KeyStoreReader
{
public static void main(String[] args)
{
// use your PKCS12 password
String password = "12345678";
try
{
FileInputStream p12data = new FileInputStream(new File("C:\\Users\\Test\\Sample_Key.p12"));
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
KeyStore ks = KeyStore.getInstance("PKCS12");
ks.load(new ByteArrayInputStream(readAllBytes(p12data)), password.toCharArray());
keyManagerFactory.init(ks, password.toCharArray());
SSLContext context = SSLContext.getInstance("SSLv3");
context.init(keyManagerFactory.getKeyManagers(), null, new SecureRandom());
System.out.println(context.getSocketFactory());
System.out.println("PASSED");
}
catch (Exception e)
{
throw new IllegalArgumentException("Exception while loading p12 data", e);
}
}
public static byte[] readAllBytes(InputStream inputStream) throws IOException {
final int bufLen = 1024;
byte[] buf = new byte[bufLen];
int readLen;
IOException exception = null;
try {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
while ((readLen = inputStream.read(buf, 0, bufLen)) != -1)
outputStream.write(buf, 0, readLen);
return outputStream.toByteArray();
} catch (IOException e) {
exception = e;
throw e;
} finally {
if (exception == null) inputStream.close();
else try {
inputStream.close();
} catch (IOException e) {
exception.addSuppressed(e);
}
}
}
}

Hope this will help to resolve the issue of the RSA private key failed to load from pkcs12. Please write your questions for any doubts or corrections.

--

--