如何在Android中实施叶子/中级证书



我已经在项目中实现了叶证书,它工作正常。请检查以下代码,现在问题是Leaf证书将在我的服务器中一年后到期,因此我想验证Leaf证书,以便该证书到期/无效时我使用中间证书?

是否有任何示例可以实现中间证书?

请帮助我!

代码: -

SSLContext sslContext = null;
        try {
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            InputStream caInput = context.getResources().openRawResource(certRawRef);
            Certificate ca;
            try {
                ca = cf.generateCertificate(caInput);
            } finally {
                caInput.close();
            }
            // Create a KeyStore containing our trusted CAs
            String keyStoreType = KeyStore.getDefaultType();
            KeyStore keyStore = KeyStore.getInstance(keyStoreType);
            keyStore.load(null, null);
            keyStore.setCertificateEntry("ca", ca);
            // Create a TrustManager that trusts the CAs in our KeyStore
            String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
            TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
            tmf.init(keyStore);
            // Create an SSLContext that uses our TrustManager
            sslContext = SSLContext.getInstance("TLSv1.2");
            sslContext.init(null, tmf.getTrustManagers(), null);
            return sslContext;
        } catch (Exception e) {
            Log.e("EXCEPTION",e.toString());
            //Print here right certificate failure issue
        }

最后我找到了答案: -

try {
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            InputStream caInputLeaf = context.getResources().openRawResource(leafCert);
            InputStream caInputInter = context.getResources().openRawResource(interCert);
            try {
                if (cf != null) {
                    ca = cf.generateCertificate(caInputLeaf);
                    URL url = new URL(URL);
                    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
                    conn.setRequestMethod("GET");
                    conn.connect();
                    chain = conn.getServerCertificates();
                    if(chain!=null && chain[0].equals(ca)) {           //Return Leaf certificate
                        return ca;
                    }
                    else{                                   //Return Intermediate certificate
                        ca = cf.generateCertificate(caInputInter);
                        return ca;
                    }
                }
            } catch (Exception cee) {
                ca = cf.generateCertificate(caInputInter);
                return ca;
            }
        } catch (Exception e) {
            Log.e("EXCEPTION", e.toString());
        }

相关内容

  • 没有找到相关文章

最新更新