Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Public Key Generation from .cer file not working on Android 28

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

like image 363
shreknit Avatar asked Aug 17 '18 01:08

shreknit


1 Answers

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.

like image 191
ehmunnehm Avatar answered Nov 16 '22 04:11

ehmunnehm