public static void main(String[] args) throws Exception
   {
      if (args.length < 1) {
         System.err.println(
               "usage: java PKCS12Import {pkcs12file} [newjksfile]");
         System.exit(1);
      }

      File fileIn = new File(args[0]);
      File fileOut;
      if (args.length > 1) {
         fileOut = new File(args[1]);
      } else {
         fileOut = new File("newstore.jks");
      }

      if (!fileIn.canRead()) {
         System.err.println(
               "Unable to access input keystore: " + fileIn.getPath());
         System.exit(2);
      }

      if (fileOut.exists() && !fileOut.canWrite()) {
         System.err.println(
               "Output file is not writable: " + fileOut.getPath());
         System.exit(2);
      }

      KeyStore kspkcs12 = KeyStore.getInstance("pkcs12");
      KeyStore ksjks = KeyStore.getInstance("jks");

      LineNumberReader in = new LineNumberReader(new InputStreamReader(System.in));
      System.out.print("Enter input keystore passphrase: ");
      char[] inphrase = in.readLine().toCharArray();
      System.out.print("Enter output keystore passphrase: ");
      char[] outphrase = in.readLine().toCharArray();

      kspkcs12.load(new FileInputStream(fileIn), inphrase);

      ksjks.load(
            (fileOut.exists())
            ? new FileInputStream(fileOut) : null, outphrase);

      Enumeration eAliases = kspkcs12.aliases();
      int n = 0;
      while (eAliases.hasMoreElements()) {
         String strAlias = (String)eAliases.nextElement();
         System.err.println("Alias " + n++ + ": " + strAlias);

         if (kspkcs12.isKeyEntry(strAlias)) {
            System.err.println("Adding key for alias " + strAlias);
            Key key = kspkcs12.getKey(strAlias, inphrase);

            Certificate[] chain = kspkcs12.getCertificateChain(strAlias);

            ksjks.setKeyEntry(strAlias, key, outphrase, chain);
         }
      }

      OutputStream out = new FileOutputStream(fileOut);
      ksjks.store(out, outphrase);
      out.close();
   }