title: How to export Certificate and private key as a single file using java code?
body: <p>My requirement is to combine a certificate and private key and then, using PEMwriter, I need to export the file.</p>
  
  <p>I used bouncycastle to generate private key and csr. Then, I submitted the CSR to CA and got the certificate. 
  THe following code is for generating keypair</p>
  
  <pre><code>KeyPair idPair = KeyPairGenerator.getInstance("RSA").genKeyPair();
  PublicKey publicKey = idPair.getPublic();
  PrivateKey privkey = idPair.getPrivate();
  </code></pre>
  
  <p>THe following code is for receiving the certificate and exporting it to .cer file.</p>
  
  <pre><code>CertStore store = response.getCertStore();
              Collection&lt;? extends Certificate&gt; certs = store
                      .getCertificates(null);
              Certificate[] chain = new Certificate[certs.size()];
  
              int i = 0;
              for (Certificate certificate : certs) {
                  chain[i++] = certificate;
              }
  
              FileOutputStream os = new FileOutputStream("cert.cer");
              os.write("-----BEGIN CERTIFICATE-----\n".getBytes("US-ASCII"));
              os.write(Base64.encodeBase64(chain[0].getEncoded(), true));
              os.write("-----END CERTIFICATE-----\n".getBytes("US-ASCII"));
              os.close();
  </code></pre>
  
  <p>Now, my goal is when I open the exported file, I must be prompted to input password to install/view the certificate. I'm really confused about this part. Previously I added password to keystore like the following</p>
  
  <pre><code>KeyStore keyStore = KeyStore.getInstance("PKCS12", "BC");
          keyStore.load(null, null);
  
          keyStore.setKeyEntry("mykey", (Key) keyPair.getPrivate(), "Password1!".toCharArray(), certz);
  
          ByteArrayOutputStream bout = new ByteArrayOutputStream();
          keyStore.store(bout, "Password1!".toCharArray()); // this is the password to open the .p12
  
          byte[] keystore = bout.toByteArray();
          bout.close();
  </code></pre>
  
  <p>But, now, I need to protect the certificate with password. Is this even possible? If so, what will be the file extension? And please guide me in the coding part (PemWriter).
  Thanks</p>