gpt4 book ai didi

java - 使用我的自签名证书创建一个 KeyStore 实例

转载 作者:太空宇宙 更新时间:2023-11-03 13:44:19 24 4
gpt4 key购买 nike

我有一个用于与我的服务器通信的自签名证书。根据 this article我可以使用我的证书创建一个 Keystore 实例。我做了同样的事情,代码工作得很好,我能够通过 HTTPS 连接进行服务器调用。

当我打印 keystore 中存在的所有证书时,它只打印我插入其中的证书。我认为此实现将指示 android 信任 AndroidCAStore 中的所有内置证书和来 self 的服务器的新自签名证书。

创建实例时,我使用了 AndroidCAStoreAndroidKeyStore 但问题是我无法将我的自签名证书添加到 keystore 。每当我调用 setCertificateEntry 时,我都会收到 UnsupportedMethodException

我想创建一个 KeyStore,其中包含来自 Android 默认 keystore 的所有默认证书和来 self 的服务器的自签名证书。如何做到这一点?

最佳答案

public static class CustomTrustManager implements X509TrustManager{

private X509TrustManager defaultTrustManager;
private X509TrustManager localTrustManager;

public CustomTrustManager(KeyStore keyStore){
try {
defaultTrustManager = createTrustManager(null);
localTrustManager = createTrustManager(keyStore);
}catch (NoSuchAlgorithmException e){
Log.e("CustomTrustManager"," Cannot create trust manager : NoSuchAlgorithm found "+e.toString());
}catch (KeyStoreException exp){
Log.e("CustomTrustManager"," Cannot create trust manager : Keystore exception"+e.toString());
}
}
@Override
public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
try {
localTrustManager.checkClientTrusted(x509Certificates, s);
} catch (CertificateException ce) {
defaultTrustManager.checkClientTrusted(x509Certificates, s);
}
}

@Override
public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
Log.e("CustomTrustManager","Checking server trust");
try {
localTrustManager.checkServerTrusted(x509Certificates, s);
} catch (CertificateException ce) {
defaultTrustManager.checkServerTrusted(x509Certificates, s);
}
}

@Override
public X509Certificate[] getAcceptedIssuers() {
X509Certificate[] first = defaultTrustManager.getAcceptedIssuers();
X509Certificate[] second = localTrustManager.getAcceptedIssuers();
X509Certificate[] result = Arrays.copyOf(first, first.length + second.length);
System.arraycopy(second, 0, result, first.length, second.length);
return result;
}

private X509TrustManager createTrustManager(KeyStore store) throws NoSuchAlgorithmException, KeyStoreException {
String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
tmf.init((KeyStore) store);
TrustManager[] trustManagers = tmf.getTrustManagers();
return (X509TrustManager) trustManagers[0];
}
}

关于java - 使用我的自签名证书创建一个 KeyStore 实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49116568/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com