X509_get_pubkey should default to checked exception

An invalid certificate would cause a RuntimeException to crop up instead
of a checked exception. Instead throw an InvalidKeyException by default
which can be caught and handled.

Bug: 28574453
Change-Id: Ib9e92c96a35d2d330a4870175a4eb5fb24fc4026
diff --git a/src/main/java/org/conscrypt/NativeCrypto.java b/src/main/java/org/conscrypt/NativeCrypto.java
index 693d702..aea2815 100644
--- a/src/main/java/org/conscrypt/NativeCrypto.java
+++ b/src/main/java/org/conscrypt/NativeCrypto.java
@@ -440,7 +440,8 @@
 
     public static native boolean[] get_X509_subjectUID(long x509ctx);
 
-    public static native long X509_get_pubkey(long x509ctx) throws NoSuchAlgorithmException;
+    public static native long X509_get_pubkey(long x509ctx) throws NoSuchAlgorithmException,
+           InvalidKeyException;
 
     public static native String get_X509_pubkey_oid(long x509ctx);
 
diff --git a/src/main/java/org/conscrypt/OpenSSLX509Certificate.java b/src/main/java/org/conscrypt/OpenSSLX509Certificate.java
index 9addc5e..a1f2db0 100644
--- a/src/main/java/org/conscrypt/OpenSSLX509Certificate.java
+++ b/src/main/java/org/conscrypt/OpenSSLX509Certificate.java
@@ -413,7 +413,7 @@
         try {
             OpenSSLKey pkey = new OpenSSLKey(NativeCrypto.X509_get_pubkey(mContext));
             return pkey.getPublicKey();
-        } catch (NoSuchAlgorithmException ignored) {
+        } catch (NoSuchAlgorithmException | InvalidKeyException ignored) {
         }
 
         /* Try generating the key using other Java providers. */
@@ -422,8 +422,7 @@
         try {
             KeyFactory kf = KeyFactory.getInstance(oid);
             return kf.generatePublic(new X509EncodedKeySpec(encoded));
-        } catch (NoSuchAlgorithmException ignored) {
-        } catch (InvalidKeySpecException ignored) {
+        } catch (NoSuchAlgorithmException | InvalidKeySpecException ignored) {
         }
 
         /*
diff --git a/src/main/native/org_conscrypt_NativeCrypto.cpp b/src/main/native/org_conscrypt_NativeCrypto.cpp
index 52e02ad..2cee798 100644
--- a/src/main/native/org_conscrypt_NativeCrypto.cpp
+++ b/src/main/native/org_conscrypt_NativeCrypto.cpp
@@ -6945,7 +6945,7 @@
         }
 #endif
 
-        throwExceptionIfNecessary(env, "X509_get_pubkey");
+        throwExceptionIfNecessary(env, "X509_get_pubkey", throwInvalidKeyException);
         return 0;
     }