title: Creating .p12 truststore with openssl
body: <p>I'm writing a Java 8 application and want to set up a simple keystore and truststore using a self-signed certificate. </p>
  
  <p>Normally this goes as follows:</p>
  
  <ol>
  <li>Create a keypair + certificate using <code>openssl</code>.</li>
  <li>Create a .jks keystore + .jks truststore using <code>keytool</code></li>
  </ol>
  
  <p>Now I'd like to only use <code>openssl</code> and create .p12 keystores instead of .jks keystores.</p>
  
  <p>Creating a .p12 keystore works great using the following commands:</p>
  
  <pre><code># Create private key and certificate
  openssl req -x509 -newkey rsa:"${rsa}" -sha256 \
      -keyout "${key}" \
      -out "${cert}" \
      -days "${days}"
  
  # Create .p12 keystore
  openssl pkcs12 -export -in "${cert}" -inkey "${key}" -out "${keystore}"
  </code></pre>
  
  <p>This keystore seems to be working correctly, as providing a corresponding .jks trustore in my Java application will get the TLS connection going. However I can't get a .p12 truststore working. </p>
  
  <p>I tried creating the truststore as suggested <a href="https://stackoverflow.com/a/23941513/3620458" title="here">here</a>:</p>
  
  <pre><code># Create .p12 truststore
  openssl pkcs12 -export -nokeys -in "${cert}" -out "${truststore}"
  </code></pre>
  
  <p>and then loading it like this:</p>
  
  <pre><code>FileInputStream fis = new FileInputStream(new File(trustorePath));
  KeyStore trustStore = KeyStore.getInstance("PKCS12");
  trustStore.load(fis, truststorePassword.toCharArray());
  fis.close();
  </code></pre>
  
  <p>but I receive the following exception in my java code:</p>
  
  <blockquote>
    <p>Unexpected error: java.security.InvalidAlgorithmParameterException:
    the trustAnchors parameter must be non-empty</p>
  </blockquote>
  
  <p>Any ideas what I'm doing wrong?</p>
  
  <p>(A working snippet using .p12 truststore with Java 8 would be greatly appreciated.)</p>