如何在Android中实现叶/中间证书固定?

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

有没有例子来实现中间证书?

请帮帮我!

码:-

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 } 

Solutions Collecting From Web of "如何在Android中实现叶/中间证书固定?"

最后我find了答案:

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