title: Reading data in a PEM certificate chain
body: <p>I can easily read in an x509 certificate in PEM format using something along the lines of:</p>
  
  <pre><code>assets.open("ca.pem").use {
      val cf = CertificateFactory.getInstance("X.509")
      keystore.setCertificateEntry("server", cf.generateCertificate(it))
  }
  </code></pre>
  
  <p>However, I now wish to include multiple trusted server certificates. The additional certificates are appended onto <code>ca.pem</code> and I use the method that claims to read multiple certificates:</p>
  
  <pre><code>val certs = cf.generateCertificates(it)
  </code></pre>
  
  <p>but only the first certificate is read in (<code>certs</code> is size 1).</p>
  
  <pre class="lang-none prettyprint-override"><code> * &lt;p&gt;In the case of a certificate factory for X.509 certificates,
   * &lt;code&gt;inStream&lt;/code&gt; may contain a sequence of DER-encoded certificates
   * in the formats described for
   * {@link #generateCertificate(java.io.InputStream) generateCertificate}.
   * In addition, &lt;code&gt;inStream&lt;/code&gt; may contain a PKCS#7 certificate
   * chain. This is a PKCS#7 &lt;i&gt;SignedData&lt;/i&gt; object, with the only
   * significant field being &lt;i&gt;certificates&lt;/i&gt;. In particular, the
   * signature and the contents are ignored. This format allows multiple
   * certificates to be downloaded at once. If no certificates are present,
   * an empty collection is returned.
  </code></pre>
  
  <p>The referenced section:</p>
  
  <pre class="lang-none prettyprint-override"><code> * &lt;p&gt;In the case of a certificate factory for X.509 certificates, the
   * certificate provided in &lt;code&gt;inStream&lt;/code&gt; must be DER-encoded and
   * may be supplied in binary or printable (Base64) encoding. If the
   * certificate is provided in Base64 encoding, it must be bounded at
   * the beginning by -----BEGIN CERTIFICATE-----, and must be bounded at
   * the end by -----END CERTIFICATE-----.
  </code></pre>
  
  <p>ca.pem looks like:</p>
  
  <pre><code>-----BEGIN CERTIFICATE-----
  ...
  -----END CERTIFICATE-----
  
  -----BEGIN CERTIFICATE-----
  ...
  -----END CERTIFICATE-----
  
  -----BEGIN CERTIFICATE-----
  ...
  -----END CERTIFICATE-----
  
  -----BEGIN CERTIFICATE-----
  ...
  -----END CERTIFICATE-----
  </code></pre>
  
  <p>Am I misunderstanding the certificate factory usage? Might this be a side effect of an input stream that does not support marking (in which case the entire stream is consumed after the first certificate)? Maybe the newlines are not allowed and the parser interprets them as end of data. Would PKCS7 be a more natural choice instead of PEM?</p>