从.cer文件生成公钥在Android 28上不起作用

时间:2018-08-17 01:21:10

标签: java android ssl-certificate x509certificate public-key-encryption

我有一种从.cer文件生成公钥的方法。我将.cer文件的内容转换为输入流,一旦获得该流,就调用此方法生成公共密钥

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();
        }
    }

一直有效,直到我们将项目更新为针对Android Pie为止。看起来Google已使用BC提供程序弃用了,这就是造成此问题的原因。如果在getInstance()中使用“ BC”,则会得到NoSuchAlgorithmException。如果我删除“ BC”并通过CertificateFactory.getInstance("X.509"),这是Google在这里建议的方法https://android-developers.googleblog.com/2018/03/cryptography-changes-in-android-p.html 我得到

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

1 个答案:

答案 0 :(得分:0)

我有同样的错误。问题是如何创建输入流。 试试这个:

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

该文件必须位于“资产”文件夹中。