Java 从证书中获取公钥

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6358555/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 05:17:50  来源:igfitidea点击:

Obtaining public key from certificate

javacryptography

提问by javi

I'm trying to obtain the public key of a Certificate using the method:

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

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

but I receive the following error:

但我收到以下错误:

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)

Does anyone know what this error is about?

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

Thanks in advance

提前致谢

采纳答案by Dan

You have the wrong class imported for X509Certificate.

您为 导入了错误的类X509Certificate

You are likely looking for java.security.cert.X509Certificatenot codec.x509.X509Certificate.

您可能正在寻找java.security.cert.X509Certificatenot codec.x509.X509Certificate

回答by Sean

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

since you are only pulling the public key, you can use the certificate class. The factory class will decide what type of a certificate to return.

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

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

If you need to cast this for antoher reason, check your imports and change it, X509Certificate should be coming from javax.security.cert

如果您出于其他原因需要强制转换,请检查您的导入并更改它,X509Certificate 应该来自 javax.security.cert