从证书获取公钥

2022-09-01 17:36:22

我正在尝试使用以下方法获取证书的公钥:

FileInputStream fin = new FileInputStream("PathToCertificate");
CertificateFactory f = CertificateFactory.getInstance("X.509");
X509Certificate certificate = (X509Certificate)f.generateCertificate(fin);
PublicKey pk = certificate.getPublicKey();

但是我收到以下错误:

Exception in thread "main" java.lang.ClassCastException: sun.security.x509.X509CertImpl cannot be cast to codec.x509.X509Certificate
        at sergas_testcertificates.Main.main(Main.java:54)

有谁知道这个错误是什么?

提前致谢


答案 1

您为 导入了错误的类。X509Certificate

您可能正在寻找不是 。java.security.cert.X509Certificatecodec.x509.X509Certificate


答案 2
X509Certificate certificate = (X509Certificate)f.generateCertificate(fin);
PublicKey pk = certificate.getPublicKey();

由于您只提取公钥,因此可以使用证书类。工厂类将决定返回哪种类型的证书。

Certificate certificate = f.generateCertificate(fin);
PublicKey pk = certificate.getPublicKey();

如果你因为 antoher 的原因需要强制转换它,请检查你的导入并更改它,X509Certificate 应该来自 javax.security.cert


推荐