我正在尝试使用以下方法获取证书的公钥:
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)
有谁知道这个错误是什么?
提前致谢
答案 0 :(得分:18)
您为X509Certificate
导入了错误的类。
您可能正在寻找java.security.cert.X509Certificate
而不是codec.x509.X509Certificate
。
答案 1 :(得分:7)
X509Certificate certificate = (X509Certificate)f.generateCertificate(fin);
PublicKey pk = certificate.getPublicKey();
由于您只提取公钥,因此可以使用证书类。工厂类将决定要返回的证书类型。
Certificate certificate = f.generateCertificate(fin);
PublicKey pk = certificate.getPublicKey();
如果您因为其他原因需要进行转换,请检查您的导入并进行更改,X509Certificate应该来自javax.security.cert