PKCS12 Java Keystore from CA and User certificate in java

The PKCS#12 format is intended for storing a private key associated with a certificate chain, and both are required (although you might not need the whole chain).
Although the PKCS12 keystore type does a good job for mapping this format to a Java KeyStore, not everything is supported for this reason.

What you’re trying to do in your first attempt is storing a certificate on its own, which won’t work.

What you’re trying to do in your second attempt (ks.setKeyEntry("SomeAlias", userCert.getPublicKey().getEncoded(), chain)) is to for a public key in place of what should be a private key (see KeyStore#setKeyEntry).

.cer file tend to be just for certificates not private keys (although of course, the extension is ultimately just an indication). If you export your .cer file from Keychain Access.app, you won’t get the private key with it (that’s what the .p12 export format is for).

EDIT about KeychainStore:

If the reason you’re trying to do this conversion is ultimately to access private keys and certificates that are already in the keychain you could load them from the KeychainStore directly:

KeyStore ks = KeyStore.getInstance("KeychainStore", "Apple");
ks.load(null, "-".toCharArray());

A couple of notes for this:

  • Any non-null, non-empty password will do to use the private key (e.g. "-".toCharArray()), as access will be prompted by the OS’s security service (like it would in other applications).
  • As far as I’m aware, there is still a bug and it only allows access to one private key/certificate pair (even if a number of pairs of private key/certificate pairs are present in the keychain)

Leave a Comment