java.security.cert.CertificateException:无法初始化

时间:2016-11-04 08:39:10

标签: java certificate digital-signature saml-2.0 opensaml

您好我尝试在另一个证书上验证证书,并在从文件中读取第一个证书时收到错误:

//Get Public Key
BasicX509Credential publicCredential = new BasicX509Credential();
File publicKeyFile = new File("keys/azurecert.cer");

if (publicKeyFile.exists()) {
    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    InputStream fileStream = new FileInputStream(publicKeyFile);
    X509Certificate certificate = (X509Certificate)certificateFactory.generateCertificate(fileStream);
            fileStream.close();

azurecert.cer由我生成,其内容是从azures(adfs)federationmetadata.xml复制粘贴的。这是一个问题吗?

<KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
    <X509Data>
        <X509Certificate>
            MIIC4jCC....
        </X509Certificate>
    </X509Data>
</KeyInfo>

我把它放在这种格式中:

—–--BEGIN CERTIFICATE--—–  
MIIDBTCCAe2gAwIBAgIQPLxWKJFunNyLetteErs/DAtQPLxWKJFunNyLMMFsdioT
MSswKQYDVQQDEyJhY2NvdW50cy5hFunNyLetteErsndpbmRvd3MubmV0XHhsStcm
....
----END CERTIFICATE----

但结果是:

java.security.cert.CertificateException: Unable to initialize, java.io.IOException: extra data given to DerValue constructor

在线:

certificateFactory.generateCertificate(inputStream2)

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:1)

确保您拥有正确的标头。而不是—–BEGIN CERTIFICATE—–--END CERTIFICATE--使用

-----BEGIN CERTIFICATE-----

-----END CERTIFICATE-----

或者,您可以以二进制格式阅读证书:删除BEGIN CERTIFICATE和END CERTIFICATE标记并解码base64