title: Insert Public Key into a KeyStore programatically
body: <p>I want to generate a key pair and insert the public and private keys into different keystores, to be used as KeyStore and TrustStore in an SSL Socket connection. I generate the KeyPair using a KeyPairGenerator, and I already have generated a signing certificate for the chain using java's keytool. Then I can insert the private key into a KeyStore like this:</p>
  
  <pre><code>PublicKey publicKey;
  PrivateKey privateKey;
  
  KeyStore keyStore = KeyStore.getInstance("JKS");
  keyStore.load(null, "storepass".toCharArray());
  
  keyStore.setKeyEntry("privatekey", privateKey, "keypass".toCharArray(), chain);
  </code></pre>
  
  <p>Using this keystore I can create a KeyManager for the SSL connection. But to create a TrustManager, I need the public key stored into a KeyStore as well, so I tried storing the public key in a key store:</p>
  
  <pre><code>PublicKey publicKey;
  
  KeyStore trustStore = KeyStore.getInstance("JKS");
  keyStore.load(null, "storepass".toCharArray());
  
  trustStore.setKeyEntry("publickey", publicKey, "public".toCharArray(), chain);
  </code></pre>
  
  <p>This returns an error: <code>java.security.KeyStoreException: Cannot store non-PrivateKeys</code>
  So I tried using <code>setCertificateEntry()</code>, but this doesn't work since it's a <code>PublicKey</code> object and I need a <code>Certificate</code>. So my question is, how can I store the PublicKey in a KeyStore programatically? Using keytool is not an option.</p>