验证()抛出java.security.无效密钥异常:提供的密钥不是RSAPublicKey示例

xoefb8l8  于 2023-01-07  发布在  Java
关注(0)|答案(1)|浏览(373)

我正在检查证书是否是自签名的。

public static void main(String[] args) throws CertificateException, IOException, GeneralSecurityException
{
    // InputStream is = new URL("http://www.d-trust.net/cgi-bin/D-TRUST_Root_CA_2_2021.crt").openStream(); // ok
    InputStream is = new URL("http://www.d-trust.net/cgi-bin/D-TRUST_Root_CA_1_2017.crt").openStream(); // not ok
    CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
    X509Certificate cert = (X509Certificate) certFactory.generateCertificate(is);
    System.out.println(cert);
    System.out.println("Self signed? " + isSelfSigned(cert));
}

public static boolean isSelfSigned(X509Certificate cert) throws GeneralSecurityException
{
    try
    {
        // Try to verify certificate signature with its own public key
        PublicKey key = cert.getPublicKey();
        System.out.println("key class: " + key.getClass().getName());
        System.out.println("Algorithm: " + key.getAlgorithm());
        cert.verify(key, new BouncyCastleProvider());
        return true;
    }
    catch (SignatureException | InvalidKeyException ex)
    {
        // Invalid signature --> not self-signed
        ex.printStackTrace();
        return false;
    }
}

我在isSelfSigned()中得到了这个异常:

java.security.InvalidKeyException: Supplied key is not a RSAPublicKey instance
    at org.bouncycastle.jcajce.provider.asymmetric.rsa.PSSSignatureSpi.engineInitVerify(Unknown Source)
    at java.security.Signature$Delegate.engineInitVerify(Signature.java:1168)
    at java.security.Signature.initVerify(Signature.java:460)
    at sun.security.x509.X509CertImpl.verify(X509CertImpl.java:483)
    at NewClass1.isSelfSigned(NewClass1.java:46)
    at NewClass1.main(NewClass1.java:35)

这种情况只发生在我的代码中的一个URL上,另一个不会。有问题的证书的算法是1.2.840.113549.1.1.10,即RSASSA-PSS。我使用的是BouncyCastle bcmail-jdk18on 1.72,它也使用bcprov-jdk18onbcpkix-jdk18on作为依赖项。
我假设这是一个自签名证书,但当然我不能肯定。

lf5gs5x2

lf5gs5x21#

原来是Java bug,我当时用的是旧的JDK8版本,在当前的JDK8版本(Amazon Corretto 1. 8. 0_352)上运行正常,感谢Topaco的帮助。

相关问题