title: Java: Invalid keystore format, when generated through code
body: <p>This has been asked a couple of times, but none provide coded test cases.  Here I give an example of the problem:</p>
  <ol>
  <li>programmatic generation of a Keystore (works)</li>
  <li>creation of certificate within that store (works)</li>
  <li>saving keystore to disk (works)</li>
  <li>listing keystore with keytool (works)</li>
  <li>loading the keystore programmatically (fails with IOException: InvalidKeystoreFormat)</li>
  </ol>
  <p>What I dont get is that in both save and load, I use <em>KeyStore.getInstance(&quot;JKS&quot;)</em>, but its failing.  Any suggestions welcome!</p>
  <p><strong>Runtime output:</strong></p>
  <pre>
  Creating private keystore at 'private.keystore'.
  Created keystore, now created signer cert
  Created signer cert, saving cert
  Reloading keystore:
  Failed to load the keystore after creation: Invalid keystore format
  </pre>
  <p><strong>Test case source:</strong></p>
  <pre class="lang-java prettyprint-override"><code>import java.io.File;
  import java.io.FileOutputStream;
  import java.io.IOException;
  import java.io.InputStream;
  import java.io.OutputStream;
  import java.security.InvalidKeyException;
  import java.security.KeyStore;
  import java.security.KeyStoreException;
  import java.security.NoSuchAlgorithmException;
  import java.security.NoSuchProviderException;
  import java.security.PrivateKey;
  import java.security.SignatureException;
  import java.security.cert.Certificate;
  import java.security.cert.CertificateException;
  import java.security.cert.X509Certificate;
  
  import sun.security.x509.X500Name;
  
  public class KeystoreCreator
  {
   private String fPrivateKeyStore;
   private String fPrivateKeyStorePassword;
   private String fPrivateKeyStoreKeyPassword;
   private String fPublicKeyCipherPassword;
   private String fPrivateKeyAlias;
  
   /**
    * @param args
    * @throws Exception 
    */
   public static void main(String[] args) throws Exception
   {
    KeystoreCreator creator = new KeystoreCreator();
     
    creator.setPrivateKeyStore(&quot;private.keystore&quot;);
    creator.setPrivateKeyStorePassword(&quot;beer123&quot;);
    
    creator.setPrivateKeyAlias(&quot;myalias&quot;);
    creator.setPrivateKeyStoreKeyPassword(&quot;beer123&quot;);
    creator.setPublicKeyCipherPassword(&quot;beer123&quot;);
  
    creator.initKeyStores();
   }
  
   public KeystoreCreator()
   {  
   }
  
   public void setPrivateKeyStore(String name)
   {
    fPrivateKeyStore=name;
   }
   public void setPrivateKeyStorePassword(String pass)
   {
    fPrivateKeyStorePassword=pass;
   }
   public void setPrivateKeyStoreKeyPassword(String pass)
   {
    fPrivateKeyStoreKeyPassword=pass;
   }
   public void setPublicKeyCipherPassword(String pass)
   {
    fPublicKeyCipherPassword=pass;
   }
   public void setPrivateKeyAlias(String alias)
   {
    fPrivateKeyAlias=alias;
   }
   
      public void initKeyStores() throws Exception
      {
          OutputStream out = null;
          File f=new File(fPrivateKeyStore);
          if (f.exists())
          {
           f.delete();
           if (f.exists())
           {
            throw new IOException(&quot;Want to remove the keystore but can't, still reported as present after removal&quot;);
           }
          }
          try
          {
           System.out.println(&quot;Creating private keystore at '&quot; + fPrivateKeyStore + &quot;'.&quot;);
           out = new FileOutputStream(fPrivateKeyStore);
           KeyStore privateKeyStore = KeyStore.getInstance(&quot;JKS&quot;);
           privateKeyStore.load(null, fPrivateKeyStorePassword.toCharArray());
           
           System.out.println(&quot;Created keystore, now created signer cert&quot;);
           X500Name x500name=getCA();
           Certificate cert = createCertificate(fPrivateKeyAlias, fPrivateKeyStoreKeyPassword, x500name, privateKeyStore);
  
           System.out.println(&quot;Created signer cert, saving cert&quot;);
           privateKeyStore.store(out, fPublicKeyCipherPassword.toCharArray());
           out.flush();
           out.close();
           //try to load it.
           KeyStore reloadedKeyStore = KeyStore.getInstance(&quot;JKS&quot;);
           try
           {
            InputStream reloadedIs=getClass().getClassLoader().getResourceAsStream(fPrivateKeyStore);
            if (reloadedIs!=null)
            {
             System.out.println(&quot;Reloading keystore:&quot;);
             reloadedKeyStore.load(reloadedIs, fPrivateKeyStorePassword.toCharArray());
            }
           }
           catch (Exception e)
           {
            System.err.println(&quot;Failed to load the keystore after creation: &quot;+e.getLocalizedMessage());
           }
          }
          catch (Exception e)
          {
           System.err.println(&quot;Failed to save the keystore: &quot;+e.getLocalizedMessage());
          }
      }
      
      private X500Name getCA() throws IOException
      {
       return new sun.security.x509.X500Name(&quot;a&quot;,&quot;b&quot;, &quot;c&quot;,&quot;d&quot;,&quot;e&quot;, &quot;GB&quot;);
      }
      
      public Certificate createCertificate( String alias, String keyPassword,
              sun.security.x509.X500Name x500Name, KeyStore keyStore ) throws NoSuchAlgorithmException,
              InvalidKeyException, CertificateException, SignatureException, NoSuchProviderException,
              KeyStoreException {     
          sun.security.x509.CertAndKeyGen keypair = new sun.security.x509.CertAndKeyGen( &quot;RSA&quot;, &quot;MD5WithRSA&quot; );
          keypair.generate( 1024 );
          PrivateKey privKey = keypair.getPrivateKey();
          X509Certificate[] chain = new X509Certificate[1];
          chain[0] = keypair.getSelfCertificate( x500Name, 7000 * 24 * 60 * 60 );
          keyStore.setKeyEntry( alias, privKey, keyPassword.toCharArray(), chain );
  
          Certificate cert = keyStore.getCertificate( alias );
          return cert;
      }
  }
  </code></pre>