'Extract ECPublicKey from a X509 certicate
I'm having trouble extracting an ECPublicKey from an X509 certifcate using Java.
The keys and certificate were created as follows
ssh-keygen -t ecdsa -f id_ecdsa
openssl pkcs8 -topk8 -in id_ecdsa -out id_ecdsa.p8
openssl req -new x509 -key id_ecdsa.p8 -out id_ecdsa.crt.der -outform der
The code used to extract the public key from the certificate is
FileInputStream fin = new FileInputStream("<path to id_ecdsa.crt.der>");
CertificateFactory cf = CertificateFactory.getInstance("X.509");
X509Certificate cert = (X509Certificate) cf.generateCertificate(fin);
PublicKey pk = cert.getPublicKey();
if (pk instanceof ECPublicKey) {
ECPublicKey key = (ECPublicKey) pk;
...
} else if (pk instanceof RSAPublicKey) {
RSAPublicKey key = (RSAPublicKey) pk;
...
}
For a certificate containing an RSA key all is ok. However if an ECDSA key is used the if(pk instanceof ECPublicKey) block is ignored.
A call to pk.getAlgorithm() yields "EC" which suggests the key is an ECDSA key.
Examination of pk with a debugger yields a type X509Key for ECDSA. For an RSA key the debugger yields RSAPublicKeyImpl.
N.B. java.security.* is used as the library.
Any help solving my problem would be greatly appreciated.
Solution 1:[1]
TrustManagerFactory tmf;
try {
tmf = TrustManagerFactory.getInstance("X509");
tmf.init((KeyStore) null);
for (TrustManager trustManager : tmf.getTrustManagers()) {
((X509TrustManager) trustManager).checkServerTrusted(
chain, authType);
}
} catch (Exception e) {
}
ECPublicKey pubkey = (ECPublicKey) chain[0].getPublicKey();
Solution 2:[2]
I found that adding Bouncy Castle as a provider appears to have fixed my issue. It appears JDK is not fitted with EC support by default.
Security.addProvider(new BouncyCastleProvider());
CertificateFactory cf = CertificateFactory.getInstance("X.509", "BC");
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Yasas Weerasekara |
| Solution 2 | John Harriott |
