Java – Creating pkcs12 using Java API failes due to error: java.security.KeyStoreException: TrustedCertEntry not supported

javakeytoolpkcs#12ssl

I am trying to create a PKCS12 keystore file using Java API. However as soon as I try to import the certificate I get the exception

java.security.KeyStoreException: TrustedCertEntry not supported

my code is:

Provider p = Security.getProvider(BouncyCastleProvider.PROVIDER_NAME);
...
KeyStore keyStore = KeyStore.getInstance("PKCS12");
keyStore.load(null, keystorePass);

keyStore.setCertificateEntry("certificate", certificate);

keyStore.setKeyEntry("key",privateKey, keypass, certChain);

The same approach works for creating JKS files but failed for PKCS12 files.

Note:
The certificate given to this program as input is created by the server using the CSR generated with the same private key used here. I.e. the public modulus for the given certificate, CSR used to generate it and the given private key are the same.

The server cert is stored in variable certChain.

Note:
I have tried OpenSSL to create the pkcs12 and I was successful, however I need to do the same using Java API.

Note: I am using JDK 7

Best Solution

Java 7 (and earlier) does not allow a trustedCert entry in a PKCS12 keystore although 8 does, perhaps because PKCS12 was designed and is usually used only for privatekey(s) and the related cert(s) and which Java puts together in the privateKey entry. You say this cert is the cert for/matching the privatekey, so it must be first in the certChain in the "key" entry, and you do not need a "cert" entry for it.