8

I have a method that generates a public key from .cer file. I conver the .cer file contents into an input stream and once I get the stream I call this method to generate public key

public static void generatePublicKey(InputStream inputStream) {
        try {
            CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509", "BC");
            Certificate certificate = certificateFactory.generateCertificate(inputStream);
            publicKey = certificate.getPublicKey();
            inputStream.close();
        } catch (CertificateException | IOException e) {
            e.printStackTrace();
        }
    }

It worked until we updated our project to target Android Pie. It looks like google deprecated using BC providers and that's causing the issue. If I use "BC" in the getInstance() I get NoSuchAlgorithmException. If I remove "BC" and pass CertificateFactory.getInstance("X.509") which was the suggested method by Google here https://android-developers.googleblog.com/2018/03/cryptography-changes-in-android-p.html I get

com.android.org.conscrypt.OpenSSLX509CertificateFactory$ParsingException: com.android.org.conscrypt.OpenSSLX509CertificateFactory$ParsingException: java.lang.RuntimeException: error:0c0000be:ASN.1 encoding routines:OPENSSL_internal:WRONG_TAG

shreknit
  • 117
  • 9

1 Answers1

3

I had the same error. The problem was how the input stream was created. Try this:

InputStream is = getAssets().open("certbase64.cer");
BufferedInputStream bis = new BufferedInputStream(is);    
CertificateFactory cf = CertificateFactory.getInstance("X.509");
Certificate cert = cf.generateCertificate(bis);

The file has to be in the "assets" folder.

ehmunnehm
  • 730
  • 1
  • 8
  • 18