Package provides a common interface for converting between different key store formats. You can copy the contents of the keys and certificates from one key store format to a different type of key store format. The package also provides the ability to export a specific certificate from a key store to the output stream, or import a certificate or a set of certificates from the input stream to a key store.

Note: Converting some key store formats is not possible.

Copying the contents of a PKCS12 type key store to a CMS type key store

The target key store provider is optional. If a provider is not specified, the Java security provider list is used. In this case, all the keys have the same password as the key store itself.
KeyStore source = KeyStore.getInstance("PKCS12"); fis =

source.load(null, PASSWORD.toCharArray());

// The KeyStore source needs to be loaded.  Example assumes that all
/ the keys have the same password as the KeyStore itself -
// in this case "PASSWORD".
KeyStoreTranslatorParameters parameter =
                  (source, PASSWORD.toCharArray(), null);

// Create a CMS KeyStore translator.  Use provider order to find
// CMSKS provider.
KeyStoreTranslator translator2CMSKS =

// Copy KeyStore
KeyStore target = translator2CMSKS.translateStore(parameter);

Exporting the certificate associated with the specified alias from the key store to the output stream.

The key store is already loaded. The certificate can be exported in BASE64 or DER format.
// Export a certificate to an output stream from a KeyStore in Base64 format
// and the name of the alias is provided.
KeyStore store = KeyStore.getInstance("JKS"); fis =
store.load(fis, PASSWORD.toCharArray());

ByteArrayOutputStream out1 = new ByteArrayOutputStream();

KeyStoreUtil.exportCertificate(out1, store, "Test User", true);

Importing a certificate from an input stream into a key store.

The certificate can be imported from input stream in binary or Base64 format. The key store must be initialized and loaded. An alias name can be provided. If an alias is not provided, the Subject DN's Common Name (CN) is used.
// Import a certificate from an input stream into a KeyStore in DER format
// and provide the name of the alias.
KeyStore store = KeyStore.getInstance("JKS");
// Create an empty keystore - certificate will be loaded here
store.load(null, PASSWORD.toCharArray());

FileInputStream fis = new FileInputStream("cacert.der");

KeyStoreUtil.importCertificate(fis, store, "MYALIAS");

Importing a set of certificates that are encoded in PKCS#7 format, from an input stream into a key store

The Subject DN's Common Name (CN) of the certificate is used as the corresponding alias of the certificate in the key store. The key store must be loaded and initialized.
KeyStoreUtil.importCertificates(fis, store);