我在其中工作的应用程序的服务器使用证书来允许请求。 例如,我已经在台式机Chrome浏览器中安装了该软件,并且工作正常。它是带有扩展名.cer
的常规证书现在我必须在我的android应用程序中也使此证书起作用,老实说,我从来没有做过,我有点迷茫。
要发出请求,我正在使用okhttp2,如本例所示:
public String makeServiceCall(String url, JSONObject data) {
final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
OkHttpClient client = new OkHttpClient();
client.setConnectTimeout(45, TimeUnit.SECONDS);
client.setReadTimeout(45, TimeUnit.SECONDS);
client.setProtocols(Arrays.asList(Protocol.HTTP_1_1));
RequestBody body = RequestBody.create(JSON, data.toString());
Request request = new Request.Builder()
.url(url)
.header("Accept","application/json")
.post(body)
.build();
try {
Response response = client.newCall(request).execute();
return response.body().string();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
到目前为止,一切都可以正常运行,但是在搜索并阅读了教程,示例等后,((本页中的许多内容)),我仍无法使其正常工作。使它与证书一起使用。
从来没有做过,并且已经有点困惑了,我希望得到以下澄清:
好的,我已经将我的证书转换为BKS并托管在res / raw文件夹中,但是我仍然无法将其成功应用于请求okhttp2 ..
我已经搜索了有关使用okhttp3进行此操作的信息,但我也无法授权请求。
This article对我很有用,但是我没有使用改造,也无法将其适配到okhttp2。
我将对如何执行的解释感激
答案 0 :(得分:2)
这是使用official okhttp3 sample code的实现。可以使用自定义证书创建受信任的OkHttpClient
。我已将.cer
证书放在res/raw
中,然后用trustedCertificatesInputStream()
方法将其红色。
CustomTrust customTrust = new CustomTrust(getApplicationContext());
OkHttpClient client = customTrust.getClient();
CustomTrust.java
import android.content.Context;
import java.io.IOException;
import java.io.InputStream;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.util.Arrays;
import java.util.Collection;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;
import okhttp3.CertificatePinner;
import okhttp3.OkHttpClient;
public final class CustomTrust {
private final OkHttpClient client;
private final Context context;
public CustomTrust(Context context) {
this.context = context;
X509TrustManager trustManager;
SSLSocketFactory sslSocketFactory;
try {
trustManager = trustManagerForCertificates(trustedCertificatesInputStream());
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, new TrustManager[]{trustManager}, null);
sslSocketFactory = sslContext.getSocketFactory();
} catch (GeneralSecurityException e) {
throw new RuntimeException(e);
}
client = new OkHttpClient.Builder()
.sslSocketFactory(sslSocketFactory, trustManager)
.connectTimeout(45, TimeUnit.SECONDS)
.readTimeout(45, TimeUnit.SECONDS)
.protocols(Arrays.asList(Protocol.HTTP_1_1))
.build();
}
public OkHttpClient getClient() {
return client;
}
/**
* Returns an input stream containing one or more certificate PEM files. This implementation just
* embeds the PEM files in Java strings; most applications will instead read this from a resource
* file that gets bundled with the application.
*/
private InputStream trustedCertificatesInputStream() {
return context.getResources().openRawResource(R.raw.certificate);
}
/**
* Returns a trust manager that trusts {@code certificates} and none other. HTTPS services whose
* certificates have not been signed by these certificates will fail with a {@code
* SSLHandshakeException}.
*
* <p>This can be used to replace the host platform's built-in trusted certificates with a custom
* set. This is useful in development where certificate authority-trusted certificates aren't
* available. Or in production, to avoid reliance on third-party certificate authorities.
*
* <p>See also {@link CertificatePinner}, which can limit trusted certificates while still using
* the host platform's built-in trust store.
*
* <h3>Warning: Customizing Trusted Certificates is Dangerous!</h3>
*
* <p>Relying on your own trusted certificates limits your server team's ability to update their
* TLS certificates. By installing a specific set of trusted certificates, you take on additional
* operational complexity and limit your ability to migrate between certificate authorities. Do
* not use custom trusted certificates in production without the blessing of your server's TLS
* administrator.
*/
private X509TrustManager trustManagerForCertificates(InputStream in)
throws GeneralSecurityException {
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
Collection<? extends Certificate> certificates = certificateFactory.generateCertificates(in);
if (certificates.isEmpty()) {
throw new IllegalArgumentException("expected non-empty set of trusted certificates");
}
// Put the certificates a key store.
char[] password = "password".toCharArray(); // Any password will work.
KeyStore keyStore = newEmptyKeyStore(password);
int index = 0;
for (Certificate certificate : certificates) {
String certificateAlias = Integer.toString(index++);
keyStore.setCertificateEntry(certificateAlias, certificate);
}
// Use it to build an X509 trust manager.
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(
KeyManagerFactory.getDefaultAlgorithm());
keyManagerFactory.init(keyStore, password);
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(
TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(keyStore);
TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {
throw new IllegalStateException("Unexpected default trust managers:"
+ Arrays.toString(trustManagers));
}
return (X509TrustManager) trustManagers[0];
}
private KeyStore newEmptyKeyStore(char[] password) throws GeneralSecurityException {
try {
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
InputStream in = null; // By convention, 'null' creates an empty key store.
keyStore.load(in, password);
return keyStore;
} catch (IOException e) {
throw new AssertionError(e);
}
}
}
答案 1 :(得分:2)
虽然已经提供了一个很好且完美的答案,但我想提供一种需要较少自定义代码的替代方法。
InputStream trustedCertificatesAsInputStream = context.getResources().openRawResource(R.raw.certificate);
List<Certificate> trustedCertificates = CertificateUtils.loadCertificate(trustedCertificatesAsInputStream);
SSLFactory sslFactory = SSLFactory.builder()
.withTrustMaterial(trustedCertificates)
.build();
SSLSocketFactory sslSocketFactory = sslFactory.getSslSocketFactory();
X509ExtendedtrustManager trustManager = sslFactory.getTrustManager().orElseThrow();
OkHttpClient okHttpClient = OkHttpClient.Builder()
.sslSocketFactory(sslSocketFactory, trustManager)
.build();
上面的库由我维护,你可以在这里找到它:GitHub - SSLContext Kickstart