title: How can I generate a key pair and insert it into a KeyStore programmatically (without using the Java KeyTool)?
body: <p>I would like to generate a key pair and insert it into a Java KeyStore programmatically. I can use the command line to do exactly what I want, but how to do that using Java code?</p>
  
  <p>Here is the command line:</p>
  
  <pre><code>keytool -genkeypair \
      -dname "cn=Unknown" \
      -alias main \
      -keyalg RSA \
      -keysize 4096 \
      -keypass 654321 \
      -keystore C:\\Users\\Felipe\\ks \
      -storepass 123456 \
      -validity 365
  </code></pre>
  
  <p>Here is the Java code I have so far:</p>
  
  <pre><code>public static void main(String[] args) {
      try (
          FileOutputStream fos = new FileOutputStream("C:\\Users\\Felipe\\ks");
      ) {
          KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
          keyPairGenerator.initialize(4096, SecureRandom.getInstance("SHA1PRNG"));
          KeyPair keyPair = keyPairGenerator.generateKeyPair();
  
          Certificate[] chain = {};
  
          KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
          keyStore.load(null, null);
          keyStore.setKeyEntry("main", keyPair.getPrivate(), "654321".toCharArray(), chain); // Error: Private key must be accompanied by certificate chain
          keyStore.store(fos, "123456".toCharArray());
      } catch (NoSuchAlgorithmException | KeyStoreException | CertificateException | IOException e) {
          e.printStackTrace();
      }
  }
  </code></pre>
  
  <p>But I keep getting the following error message: <code>Private key must be accompanied by certificate chain</code>.</p>
  
  <p>I think I should create a certificate and insert it into the certificate array, but how to do that?</p>