public static void saveToProtectedStore(PrivateKey privateKey,Certificate certificate,File storeLocation,String alias,String privateKeyPassword,String keyStorePassword,String keyStoreType) throws IOException, KeyStoreException, NoSuchProviderException, NoSuchAlgorithmException, CertificateException {
  KeyStore store=null;
  if (keyStoreType.equals("PKCS12")) {
    store=KeyStore.getInstance(keyStoreType,CryptoUtil.getSecurityProviderName(KeyStore.class));
  }
 else   store=KeyStore.getInstance(keyStoreType);
  store.load(null,null);
  Certificate[] chain=new Certificate[1];
  chain[0]=certificate;
  if (privateKeyPassword != null)   store.setKeyEntry(alias,privateKey,privateKeyPassword.toCharArray(),chain);
 else   store.setKeyEntry(alias,privateKey,null,chain);
  FileOutputStream fOut=new FileOutputStream(storeLocation);
  try {
    store.store(fOut,keyStorePassword == null ? null : keyStorePassword.toCharArray());
  }
  finally {
    fOut.close();
  }
}

public static void saveToProtectedStore ( PrivateKey privateKey , Certificate certificate , File storeLocation , String alias , String privateKeyPassword , String keyStorePassword , String keyStoreType ) throws IOException , KeyStoreException , NoSuchProviderException , NoSuchAlgorithmException , CertificateException { KeyStore store = null ; if ( keyStoreType . equals ( "PKCS12" ) ) { store = KeyStore . getInstance ( keyStoreType , CryptoUtil . getSecurityProviderName ( KeyStore . class ) ) ; } else store = KeyStore . getInstance ( keyStoreType ) ; store . load ( null , null ) ; Certificate [ ] chain = new Certificate [ 1 ] ; chain [ 0 ] = certificate ; if ( privateKeyPassword != null ) store . setKeyEntry ( alias , privateKey , privateKeyPassword . toCharArray ( ) , chain ) ; else store . setKeyEntry ( alias , privateKey , null , chain ) ; FileOutputStream fOut = new FileOutputStream ( storeLocation ) ; try { store . store ( fOut , keyStorePassword == null ? null : keyStorePassword . toCharArray ( ) ) ; } finally { fOut . close ( ) ; } }
save the private key to a jks or pfx ( pkcs12 ) - keystore .
