0

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.

President James K. Polk
  • 40,516
  • 21
  • 95
  • 125
John Harriott
  • 49
  • 2
  • 5

2 Answers2

0

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");
John Harriott
  • 49
  • 2
  • 5
0
    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();
  • 1
    As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Mar 08 '22 at 08:05