Obtaining public key from certificate
我正在尝试使用以下方法获取证书的公钥:
1 2 3 4 | FileInputStream fin = new FileInputStream("PathToCertificate"); CertificateFactory f = CertificateFactory.getInstance("X.509"); X509Certificate certificate = (X509Certificate)f.generateCertificate(fin); PublicKey pk = certificate.getPublicKey(); |
但我收到以下错误:
1 2 | 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 2 | X509Certificate certificate = (X509Certificate)f.generateCertificate(fin); PublicKey pk = certificate.getPublicKey(); |
因为您只提取公钥,所以可以使用证书类。工厂类将决定返回哪种类型的证书。
1 2 |
如果出于其他原因需要强制转换此证书,请检查导入并进行更改,x509证书应来自javax.security.cert。