Ser*_*o76 5 android certificate okhttp
我工作的应用程序的服务器使用证书来允许请求。例如,我已将其安装在桌面 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;
}
}
Run Code Online (Sandbox Code Playgroud)
到目前为止,一切都完美无缺,但是在搜索和阅读教程、示例等(其中许多来自本页)之后,我还没有设法让它工作。使其与证书一起使用。
从未这样做过,并且已经有点困惑,我将不胜感激以下澄清:
好的,我已经将我的证书转换为 BKS 并托管在 res/raw 文件夹中,但我仍然无法将其成功应用于请求 okhttp2 ..
我已经搜索了有关使用 okhttp3 执行此操作的信息,但我也无法授权这些请求。
这篇文章对我很有用,但我没有使用改造,将其调整为 okhttp2 也不起作用。
我将不胜感激如何做到这一点的解释
ami*_*phy 10
这是使用官方 okhttp3 示例代码的实现。可以OkHttpClient使用自定义证书创建受信任的证书。我已经将.cer证书放入res/raw然后使用该trustedCertificatesInputStream()方法读取它。
CustomTrust customTrust = new CustomTrust(getApplicationContext());
OkHttpClient client = customTrust.getClient();
Run Code Online (Sandbox Code Playgroud)
自定义信任.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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
尽管已经提供了一个很好且完美的答案,但我想提供一个需要较少自定义代码的替代方案。
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();
Run Code Online (Sandbox Code Playgroud)
上述库由我维护,您可以在这里找到它:GitHub - SSLContext Kickstart
| 归档时间: |
|
| 查看次数: |
6842 次 |
| 最近记录: |