读取PEM证书链中的数据

时间:2018-01-03 18:38:19

标签: java android ssl x509 jsse

我可以使用以下内容轻松读取PEM格式的x509证书:

assets.open("ca.pem").use {
    val cf = CertificateFactory.getInstance("X.509")
    keystore.setCertificateEntry("server", cf.generateCertificate(it))
}

但是,我现在希望包含多个可信服务器证书。其他证书附加到ca.pem,我使用声称读取多个证书的方法:

val certs = cf.generateCertificates(it)

但只读入第一个证书(certs的大小为1)。

 * <p>In the case of a certificate factory for X.509 certificates,
 * <code>inStream</code> may contain a sequence of DER-encoded certificates
 * in the formats described for
 * {@link #generateCertificate(java.io.InputStream) generateCertificate}.
 * In addition, <code>inStream</code> may contain a PKCS#7 certificate
 * chain. This is a PKCS#7 <i>SignedData</i> object, with the only
 * significant field being <i>certificates</i>. 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.

参考部分:

 * <p>In the case of a certificate factory for X.509 certificates, the
 * certificate provided in <code>inStream</code> 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-----.

ca.pem看起来像:

-----BEGIN CERTIFICATE-----
...
-----END CERTIFICATE-----

-----BEGIN CERTIFICATE-----
...
-----END CERTIFICATE-----

-----BEGIN CERTIFICATE-----
...
-----END CERTIFICATE-----

-----BEGIN CERTIFICATE-----
...
-----END CERTIFICATE-----

我是否误解了证书工厂的使用情况?这可能是不支持标记的输入流的副作用(在这种情况下,整个流在第一个证书之后被消耗)?也许不允许换行,解析器将它们解释为数据的结尾。 PKCS7会更自然而不是PEM吗?

2 个答案:

答案 0 :(得分:2)

确实删除换行符会让解析器感到满意。

-----BEGIN CERTIFICATE-----
...
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
...
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
...
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
...
-----END CERTIFICATE-----

答案 1 :(得分:1)

BouncyCastle&#39; CertificateFactory将忽略条目之间的空格:

import org.bouncycastle.jcajce.provider.asymmetric.x509.CertificateFactory

assets.open("ca.pem").use { pem ->
    val certreader = CertificateFactory()
    certreader.engineGenerateCertificates(pem)
              .forEach { cert ->
                  keystore.setCertificateEntry("server", cert)
              }
}

我避免引用外部依赖关系的响应,但如果您在此区域工作,Bouncy Castle可能会提供其他实用程序。