I have answered some questions look like your issue as the following:
Read in PKCS12/P12 Client Cert file for Android App
Android volley self signed HTTPS trust anchor for certification path not found
You will find
private SSLSocketFactory getSSLSocketFactory_KeyStore(String keyStoreType, int keystoreResId, String keyPassword)
throws CertificateException, KeyStoreException, IOException, NoSuchAlgorithmException, KeyManagementException {
InputStream caInput = getResources().openRawResource(keystoreResId);
// creating a KeyStore containing trusted CAs
if (keyStoreType == null || keyStoreType.length() == 0) {
keyStoreType = KeyStore.getDefaultType();
}
KeyStore keyStore = KeyStore.getInstance(keyStoreType);
keyStore.load(caInput, keyPassword.toCharArray());
// creating a TrustManager that trusts the CAs in the KeyStore
String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
tmf.init(keyStore);
TrustManager[] wrappedTrustManagers = getWrappedTrustManagers(tmf.getTrustManagers());
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, wrappedTrustManagers, null);
return sslContext.getSocketFactory();
}
and getSSLSocketFactory_Certificate
for .cert
file.
As in the first link above, in your project you can call one of the two methods:
If using keystore file:
SSLSocketFactory sslSocketFactory = getSSLSocketFactory_KeyStore("PKCS12", R.raw.androidpkcs12, "123456789");
If using certificate file:
SSLSocketFactory sslSocketFactory = getSSLSocketFactory_Certificate("PKCS12", R.raw.androidpkcs12_cert);
P/S: If these methods are inside a non-activity class, to avoid NPE, you must pass Context
from your Activity to that class (as inside the first link above).
Hope this helps!
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…