Obtaining public key from certificate
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");
X509Cer开发者_StackOverflow中文版tificate 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
You have the wrong class imported for X509Certificate
.
You are likely looking for java.security.cert.X509Certificate
not codec.x509.X509Certificate
.
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
精彩评论