title: How to create PKCS#12 format file with client public certificate and private key using java program
body: <p>I have client public certificate and private key file in the form of .pem format files.</p>
  
  <p>Can anyone of you help me how to create PKCS#12 format file with those files using java program.</p>
  
  <p>Here i have added my code </p>
  
  <pre><code>Path path = Paths.get(new File("User_privkey.pem").getAbsolutePath());
          Path certPath = Paths.get(new File("User.pem").getAbsolutePath());
          try {
              // Used to read User_privkey.pem file to get private key
              PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(Files.readAllBytes(path));
              KeyFactory keyFactory = KeyFactory.getInstance("RSA");
              PrivateKey privateKey = keyFactory.generatePrivate(spec);
  
              //  Used to read user certificate 
              CertificateFactory factory = CertificateFactory.getInstance("X.509");
              Certificate cert = factory.generateCertificate(Files.newInputStream(certPath, null));
  
              KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
              // add it to the keystore
              ks.setKeyEntry("MyPKCSEntry", privateKey, "Temp".toCharArray(), new Certificate[] { cert });
  
              File file = new File("CERTIFICATE_CUSTOMPATH");
              OutputStream out = new FileOutputStream(file);
              ks.store(out, "Temp".toCharArray());
              out.close();
  
          } catch (Exception e) {
              System.out.println("Exception got caught" + e.getMessage());
          }
  </code></pre>