从证书中获取公钥

时间:2011-06-15 13:37:06

标签: java cryptography

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

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)

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

提前致谢

2 个答案:

答案 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